Autolayout 动画之键盘弹出

使用自动布局中,最不好操作的就是动画。简单的如键盘弹出的动画还好,涉及到复杂的曲线等不规则动画,那就头疼了。本文将讲解当键盘弹出时,如何修改约束。

案例下载地址:

https://github.com/saitjr/AutolayoutKeyboardDemo.git

环境信息:

Mac OS X 10.10.3

Xcode 6.3

iOS 8.3

正文

一、放入UITextField并添加相应约束

添加控件与约束
添加控件与约束

二、将下边距约束关联到对应控制器中

关联约束到控制器
关联约束到控制器
关联下边距约束
关联下边距约束

三、注册与移除键盘通知


#import "ViewController.h"

@interface ViewController ()

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

@end

@implementation ViewController

- (void)dealloc {
    
    // 移除键盘通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    // 注册键盘通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrameNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideNotification:) name:UIKeyboardWillHideNotification object:nil];
}

// 键盘改变高度通知处理
- (void)keyboardWillChangeFrameNotification:(NSNotification *)notification {
    
    
}

// 键盘隐藏通知处理
- (void)keyboardWillHideNotification:(NSNotification *)notification {
    
    
}

@end

四、处理键盘通知

  1. 键盘弹出事件处理

- (void)keyboardWillChangeFrameNotification:(NSNotification *)notification {
    
    // 获取键盘基本信息(动画时长与键盘高度)
    NSDictionary *userInfo = [notification userInfo];
    CGRect rect = [userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGFloat keyboardHeight = CGRectGetHeight(rect);
    CGFloat keyboardDuration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 修改下边距约束
    _bottomConstraint.constant = keyboardHeight;
    
    // 更新约束
    [UIView animateWithDuration:keyboardDuration animations:^{
        
        [self.view layoutIfNeeded];
    }];
}
  1. 键盘隐藏事件处理

- (void)keyboardWillHideNotification:(NSNotification *)notification {
    
    // 获得键盘动画时长
    NSDictionary *userInfo = [notification userInfo];
    CGFloat keyboardDuration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 修改为以前的约束(距下边距20)
    _bottomConstraint.constant = 20;
    
    // 更新约束
    [UIView animateWithDuration:keyboardDuration animations:^{
        
        [self.view layoutIfNeeded];
    }];
}

更多相关文章:

?Autolayout案例讲解

发表评论

电子邮件地址不会被公开。