首页 文章

textFieldDidEndEditing在不需要时移动屏幕

提问于
浏览
5

在我的应用程序中,我的UITextField位于键盘顶部的下方,因此我必须向上移动视图,以便在编辑时键盘上可以看到文本字段 . 为了做到这一点,我使用了UITextFieldDelegate方法textFieldDidBeginEditing: . 然后在方法textFieldDidEndEditing:中,我将视图向下移动 .

当我尝试在文本字段之间切换时会出现问题 . 当我这样做时,委托调用方法textFieldDidEndEditing:然后立即调用textFieldDidBeginEditing:对于另一个文本字段,这使得视图向下然后立即向上,所以它看起来像屏幕颠簸 . 这种效果有解决方法吗?

4 回答

  • 1

    我刚刚遇到了完全相同的问题,这就是我遇到的解决方案 .

    设置一个单独的方法来处理textField键盘的处理,并将self.view.center重新对齐放在那里 . 这样,您可以确保textFieldDidEndEditing方法保持独立 .

    如果我没有正确解释自己,这是一个例子 . 请注意,当用户点击textField时,我会在导航栏中放置一个DONE按钮(因为它是数字小键盘),尽管您可以将此方法链接到普通键盘上的DONE按钮:

    - (void)textFieldDidBeginEditing:(UITextField *)textField {
        UIBarButtonItem *hideKeyboardButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(resignResponder:)];
        [self.navigationItem setRightBarButtonItem:hideKeyboardButton animated:YES];
    }
    
    - (void)textFieldDidEndEditing:(UITextField *)textField {
    
    //Nothing needs to go here anymore
    
    }
    
    - (void)resignResponder:(id)sender {
        [textField resignFirstResponder];
        //Use core animation instead of the simple action below in order to reduce 'snapback'
        self.view.center = CGRectMake(0, 0, 320, 480);
    }
    
  • 0

    只需检入您所在的文本字段(例如,给它们 tag s) . 然后根据此信息,移动或不移动您的视图 .

  • 0

    我认为移动文本字段的最佳方法是注册通知

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

    在keyboardWillShow中修改textfield框架:&keyboardWillHide:

  • 0

    我使用了一种不同的方法来解决这个问题:当从一个编辑控件切换到另一个编辑控件时(field1 - > field2),您会收到以下消息:

    • textFieldShouldBeginEditing(field2)

    • textFieldShouldEndEditing(field1)

    • textFieldDidEndEditing(field1)

    • textFieldDidBeginEditing(field2)

    我所做的是使用计数器变量(x):

    • 在textFieldShouldBeginEditing中添加x = 1

    • 在textFieldShouldEndEditing中添加x- = 1

    然后:

    如果x <0,textFieldDidEndEditing中的

    • 将控件拉伸到原始位置
      如果x> 0,textFieldDidBeginEditing中的
    • 将汇总控件

相关问题