Masonry约束动画 以及 键盘弹起

要求
当键盘挡住输入框时,输入框自动向上弹到键盘上方。
实现
这里需要使用到Masonry的另外一个方法mas_updateConstraints。这个方法用于更新控件约束。
具体的实现方式可以下载Demo来看,这里只贴出键盘弹出时的处理代码:

- (void)keyboardWillChangeFrameNotification:(NSNotification *)notification { 
// 获取键盘基本信息(动画时长与键盘高度)
 NSDictionary *userInfo = [notification userInfo]; 
CGRect rect = 
[userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];

 CGFloat keyboardHeight = CGRectGetHeight(rect); 
CGFloat keyboardDuration = 
[userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];

 // 修改下边距约束
 [_textField mas_updateConstraints:^(MASConstraintMaker *make) { 
make.bottom.mas_equalTo(-keyboardHeight); }]; 

// 更新约束

 [UIView animateWithDuration:keyboardDuration animations:^{
 [self.view layoutIfNeeded]; }];
}

总结:

  1. 可以给控件添加left/right/top/bottom/size/height/width/insert约束;
  2. 库提供了三个方法,mas_makeConstraints添加约束,mas_updateConstraints修改约束,mas_remakeConstraints清除以前约束并添加新约束;
  3. 可以通过view.mas_bottom获得view的某个约束;
  4. 在约束的block中,使用make来给当前控件添加约束。
 
原文地址:https://www.cnblogs.com/cranz-jf/p/5225202.html