Autolayout 动画之键盘弹出

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

案例下载地址:

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


环境信息
Mac OS X 10.10.3
Xcode 6.3
iOS 8.3

正文

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

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

三、注册与移除键盘通知

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

#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. 键盘弹出事件处理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

- (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. 键盘隐藏事件处理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

- (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案例讲解