为什么UITextField在resignFirstResponder上设置动画?

时间:2015-11-05 12:03:18

标签: ios objective-c animation uitextfield resignfirstresponder

从iOS 8开始,表单中的UITextField表现得非常奇怪。如果我单击另一个文本字段或按键盘上的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];
}

3 个答案:

答案 0 :(得分:4)

试试这个

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

我想我应该解决你的问题。在UITextField: When beginning input, textfield bounces up, and then bounces down

上发了一些类似的帖子

IOS8 Text in TextField Bounces on Focus

如果我们还有问题,请告诉我

答案 1 :(得分: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;
    }
}

答案 2 :(得分:0)

尝试将代码包装在此

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