如何使用自动布局避免 UITextField 和键盘之间的冲突?

How to avoid collision between UITextField and Keyboard using auto layout?

1.I不喜欢用任何第三方框架做,只有约束有没有可能?

好的,我试过了:)

使用约束 IBOutlet 我需要更新它..

-(void)keyboardDidShow:(NSNotification*)aNotification{
    NSDictionary* info = [aNotification userInfo];

    double animationduration =[info[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect keyboardEndFrame =[info[UIKeyboardFrameEndUserInfoKey] CGRectValue];

    NSLog(@"this is user info notification keyboard did show==%@",info);
}

指导我的朋友们实现这个:)

按照以下步骤操作:

  • 每当键盘出现时,只需更改 constant 的输出 根据您的需要进行约束。
  • 然后通过调用 [self updateConstraintIfNeeded]
  • 更新约束
  • 然后通过调用 [self layoutIfNeeded]
  • 更新视图布局
  • 每当键盘出现故障时,将您的常量改回 原来的
  • 再次关注 3 和 4

提示:
在 UIView 动画块中调用布局更新调用将帮助您平滑过渡。

如果你想获得键盘尺寸:

- (void)keyboardWillShow:(NSNotification*)notification {
   NSDictionary *info = [notification userInfo];
   CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
   CGFloat deltaHeight = kbSize.height - _currentKeyboardHeight; 
   // Write code to adjust views accordingly using deltaHeight
   _currentKeyboardHeight = kbSize.height;

}

就这些了。

您必须更改 NSLayoutConstraint 中的 constant 属性。那你得刷新布局了

如果您的 IBOutlet 是:

@property (nonatomic, weak) IBOutlet NSLayoutConstraint *bottomConstraint;

并且NSLayoutConstraint中的初始常数值为bottomInitialValue

代码应该是:

- (void) keyboardDidShow:(NSNotification*) aNotification
{
    NSDictionary* info = [aNotification userInfo];

    double animationduration =[info[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect keyboardEndFrame =[info[UIKeyboardFrameEndUserInfoKey] CGRectValue];

    bottomConstraint.constant = keyboardEndFrame.size.height + bottomInitialValue;
    [self.view layoutIfNeeded];
}

当键盘消失时,您必须将constant 属性设置为初始值:

bottomConstraint.constant = bottomInitialValue;
[self.view layoutIfNeeded];

获取imageView 顶部约束IBOutlet

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *constraintImageViewTop;

向上

- (void)keyboardWillShow:(NSNotification*)notification
 {
    NSDictionary *info = [notification userInfo];
    CGSize kbHeight = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    constraintImageViewTop.constant = constraintImageViewTop.constant - kbSize.height;
 }

向下

- (void)keyboardWillHide:(NSNotification *)notification
 {
    NSDictionary *info = [notification userInfo];
    CGSize kbHeight = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    constraintImageViewTop.constant = constraintImageViewTop.constant + kbSize.height;
 }

使 PhoneNumber(textfield) 底部约束优先级低