显示键盘时隐藏 UITextField

UITextField hidden while keyboard is showing

在我的应用程序中,我有这个登录屏幕:

在第一个测试字段上方我有一张图片,Interface Builder 中的配置如下:

现在,当我点击 UITextField 时,它们应该向上移动,否则在 iPhone 4/4 秒后,该字段将被键盘覆盖。 现在我使用以下代码:

-(void)textFieldDidBeginEditing:(UITextField *)textField {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.35f];
    CGRect frameView = self.view.frame;
    CGRect frameImage = self.imageViewLogo.frame;
    CGRect frameTextFieldUsername = self.textFieldUsername.frame;
    CGRect frameTextFieldPassword = self.textFieldPassword.frame;
    CGRect frameButtonLogin = self.buttonLogin.frame;
    frameView.origin.y = -100;
    frameImage.origin.y = -100;
    frameTextFieldUsername.origin.y = -100;
    frameTextFieldPassword.origin.y = -100;
    frameButtonLogin.origin.y = -100;
    [self.view setFrame:frameView];
    [self.imageViewLogo setFrame:frameImage];
    [self.textFieldUsername setFrame:frameTextFieldUsername];
    [self.textFieldPassword setFrame:frameTextFieldPassword];
    [self.buttonLogin setFrame:frameButtonLogin];
    [UIView commitAnimations];
}

当我尝试 运行 模拟器或真实设备上的应用程序时,视图会向上滚动 100,但图像、文本字段和按钮不会向上滚动...我认为问题取决于约束,你能帮我解决这个问题吗? 谢谢

您尝试执行此操作的方式会给您带来麻烦。当您给出 frame 的硬编码值时。

尝试使用 keyboard avoiding library 这是更好、更安全的方法。

-(void)textFieldDidBeginEditing:(UITextField *)textField {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.35f];
    CGRect frameView = self.view.frame;
    CGRect frameImage = self.imageViewLogo.frame;
    CGRect frameTextFieldUsername = self.textFieldUsername.frame;
    CGRect frameTextFieldPassword = self.textFieldPassword.frame;
    CGRect frameButtonLogin = self.buttonLogin.frame;
    frameView.origin.y = -100;
    // no need of changing frames of TextFields inside the View, Just change the y-padding of View
    [self.view setFrame:frameView];
    [UIView commitAnimations];
}

将 y 填充减少到 -120 并检查

希望对你有帮助谢谢

如果您的视图设置为使用 AutoLayout,则更改框架将不起作用。

您应该订阅 UIKeyboardWillChangeFrameNotification 并在那里进行更改。在约束的情况下,您将在此处更新约束常量并在父视图上调用 -setNeedsUpdateConstraints

如果你想支持外部键盘,你必须弄清楚键盘是出现还是消失。

否则你可以监听 UIKeyboardWillShowNotificationUIKeyboardWillHideNotification

嗨,简单易行的技巧是:-

在你的 class 中取出用户名或电子邮件 ID 文本字段的最高约束并在文本字段上确实开始编辑委托减少约束的常量值所以当你 select 文本字段和在 textField 结束编辑委托时,再次将约束的常量值设置为前一个,这样它将重置到前一个位置。

例如:-假设您在 Storyboard 中设置的 Top Constraint 值为 150

-(void)textFieldDidBeginEditing:(UITextField *)textField {
   _topConstraint.constant = 10.00; 
[UIView animateWithDuration:0.5f animations:^{
                    [self.view layoutIfNeeded];
                            }];
}
-(void)textFieldDidEndEditing:(UITextField *)textField {
   _topConstraint.constant = 150.00; 
[UIView animateWithDuration:0.5f animations:^{
                    [self.view layoutIfNeeded];
                            }];
}

希望对您有所帮助。

当键盘自带时自动启动 textFields 不需要使用第三方 类。

创建静态 tableView 并在每个静态单元格中设计每个 textFields 和按钮。 TableView 在键盘出现时自动处理自动向上 textFields