为什么UITextField在resignFirstResponder时会发生动画?

15

iOS 8以来,在表单中,UITextFields的行为非常奇怪。如果我点击另一个文本字段或按下键盘上的Tab键,则输入的文本会向上动画,然后迅速重新出现。每次在视图加载后都会发生这种情况,以及之后的某个时间。

它看起来像这样:

Animation

我的代码如下:

#pragma mark - <UITextFieldDelegate>

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.passwordTextField) {
        [self loginButtonClicked:nil];
    } else if (textField == self.emailTextField) {
        [self.passwordTextField becomeFirstResponder];
    }

    return YES;
}

编辑:

看起来这个问题是由我的键盘监听器引起的:

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


- (void)keyboardWillHide:(NSNotification *)sender
{
    self.loginBoxBottomLayoutConstraint.constant = 0;

    [self.view layoutIfNeeded];
}

- (void)keyboardWillShow:(NSNotification *)sender
{
    CGRect frame = [sender.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGRect newFrame = [self.view convertRect:frame fromView:[[UIApplication sharedApplication] delegate].window];
    self.loginBoxBottomLayoutConstraint.constant = CGRectGetHeight(newFrame);

    [self.view layoutIfNeeded];
}

你在检查模拟器吗?如果是,你使用外部键盘了吗? - aman.sood
在模拟器和真实设备上,无论是否连接键盘,情况都是一样的。 - gklka
你能否创建一个带有文本框的示例项目,因为很难理解可能的原因。 - aman.sood
我创建了一个空的演示项目,现在我确定动画是我的键盘监听器的副作用。我编辑了我的初始问题以包含该代码。 - gklka
请告诉我什么是'loginBoxBottomLayoutConstraint'和'noticeView',这样我就可以在我的项目中复制它。 - aman.sood
显示剩余7条评论
3个回答

4

试试这个

 - (void)textFieldDidEndEditing:(UITextField *)textField
 {
    [textField layoutIfNeeded]; 
 }

我猜应该可以解决你的问题。在这里有一些类似的帖子。

iOS8中,聚焦TextField时文本会反弹

如果仍然存在问题,请告诉我。


4
问题似乎在于您正在执行代码片段。
-(void)keyboardWillShow:(NSNotification *)sender

即使键盘已经激活,这会导致一些扭曲。一个小的解决方法是,在调整框架之前检查键盘是否已经激活,如下所示。
bool isKeyboardActive = false;

-(void)keyboardWillHide:(NSNotification *)sender

{

    self.boxBottomConstraint.constant = 0;
    [self.view layoutIfNeeded];
    isKeyboardActive = false;
}


-(void)keyboardWillShow:(NSNotification *)sender

{

    if (!isKeyboardActive) {
        CGRect frame = [sender.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        CGRect newFrame = [self.view convertRect:frame fromView:[[UIApplication sharedApplication] delegate].window];
        self.boxBottomConstraint.constant = CGRectGetHeight(newFrame);
        [self.view layoutIfNeeded];
        isKeyboardActive = true;
    }
}

0

尝试将您的代码包装在这里

[UIView performWithoutAnimation:^{// Changes we don't want animated here
}];

像什么?我不明白我应该将什么放入非动画块中。 - gklka
我会假设 [self.view layoutIfNeeded]; - Alistra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接