使用自动布局中,最不好操作的就是动画。简单的如键盘弹出的动画还好,涉及到复杂的曲线等不规则动画,那就头疼了。本文将讲解当键盘弹出时,如何修改约束。
文章太过久远,可能已不具备参考价值。没删,只因为留作纪念。
案例下载地址:
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];
[[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
|
四、处理键盘通知
- 键盘弹出事件处理
- (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]; }]; }
|
- 键盘隐藏事件处理
- (void)keyboardWillHideNotification:(NSNotification *)notification {
NSDictionary *userInfo = [notification userInfo]; CGFloat keyboardDuration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
_bottomConstraint.constant = 20;
[UIView animateWithDuration:keyboardDuration animations:^{
[self.view layoutIfNeeded]; }]; }
|
更多相关文章:
?Autolayout案例讲解