gpt4 book ai didi

ios - uikeyboardwillhidenotification 滚动时调用方法两次

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:14:43 31 4
gpt4 key购买 nike

我有一个带有 UIScrollView 的 View 并且有很多 UITextField 我在触摸 View 后关闭键盘并且它工作正常同时我想在滚动时关闭键盘风景。我的问题是当我 ScrollView 时它正在关闭键盘但它调用方法 (keyboardWillHide) 两次,这对我设置屏幕错误造成了问题。如何防止调用该方法两次?

我的代码:

- (void)viewDidLoad {
[super viewDidLoad];

UITapGestureRecognizer* tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeTextInput)];
tapGesture.cancelsTouchesInView = NO;
[self.view addGestureRecognizer:tapGesture];

_scrllView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
}

- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide)
name:UIKeyboardWillHideNotification
object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];

[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillShowNotification
object:nil];

[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillHideNotification
object:nil];
}

-(void)keyboardWillHide {

if (self.view.frame.origin.y >= 0)
{
[self setViewMovedUp:YES];
}
else if (self.view.frame.origin.y < 0)
{
[self setViewMovedUp:NO];
}
}

-(void)setViewMovedUp:(BOOL)movedUp{

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];

CGRect rect = self.view.frame;
if (movedUp)
{
if (self.view.frame.origin.y != -kOFFSET_FOR_KEYBOARD){

rect.origin.y -= kOFFSET_FOR_KEYBOARD;
rect.size.height += kOFFSET_FOR_KEYBOARD;
}
}
else
{
rect.origin.y += kOFFSET_FOR_KEYBOARD;
rect.size.height -= kOFFSET_FOR_KEYBOARD;
}
self.view.frame = rect;
[UIView commitAnimations];
}

最佳答案

尝试保留一个 BOOL keyboardIsUp,如果键盘弹起则为真,然后在输入函数 keyboardWillHide 时询问 keyboardIsUp 是否为真。如果是真的,继续。如果为假,则退出函数:

-(void)keyboardWillHide 
{
if (keyboardIsUp == NO)
return;
else
//your code

您的函数仍将被调用两次或更多次,但只会执行一次其功能。只需确保在适当的时候将 keyboardIsUp 设置为 YES 和 NO。

关于ios - uikeyboardwillhidenotification 滚动时调用方法两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30845026/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com