码迷,mamicode.com
首页 > 移动开发 > 详细

IOS开发——UI进阶篇(六)键盘处理

时间:2015-07-27 01:51:51      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

一、键盘通知
我们经常需要在键盘弹出或者隐藏的时候做一些特定的操作,因此需要监听键盘的状态

键盘状态改变的时候,系统会发出一些特定的通知
UIKeyboardWillShowNotification // 键盘即将显示
UIKeyboardDidShowNotification // 键盘显示完毕
UIKeyboardWillHideNotification // 键盘即将隐藏
UIKeyboardDidHideNotification // 键盘隐藏完毕
UIKeyboardWillChangeFrameNotification // 键盘的位置尺寸即将发生改变
UIKeyboardDidChangeFrameNotification // 键盘的位置尺寸改变完毕

系统发出键盘通知时,会附带一下跟键盘有关的额外信息(字典),字典常见的key如下:
UIKeyboardFrameBeginUserInfoKey // 键盘刚开始的frame
UIKeyboardFrameEndUserInfoKey // 键盘最终的frame(动画执行完毕后)
UIKeyboardAnimationDurationUserInfoKey // 键盘动画的时间
UIKeyboardAnimationCurveUserInfoKey // 键盘动画的执行节奏(快慢)

技术分享技术分享

         点击Text Field弹出文字时  让Text Field始终跟着键盘移动,并且贴着键盘上面

 

正因为键盘状态改变的时候,系统会发出一些特定的通知,我们可以监听键盘的状态

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

实现方法:

/**
 *  监听键盘的frame即将发生改变的时候调用
 */
- (void)keyboardWillChange:(NSNotification *)note
{
    // 获得键盘最后的frame
    CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    // 修改底部约束
    self.bottomSpace.constant = self.view.frame.size.height - frame.origin.y;

    //  执行动画
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
}

 // 触摸屏幕退出键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // 文本框不再是第一响应者,就会退出键盘
//    [self.textField resignFirstResponder];
    
//    [self.textField endEditing:YES];
    
    [self.view endEditing:YES];
}

 

userInfo是系统提供的字典属性
@property (nullable, readonly, copy) NSDictionary *userInfo;
打印的结果如下:
UIKeyboardAnimationCurveUserInfoKey = 7; // 动画曲线动画
UIKeyboardAnimationDurationUserInfoKey = "0.25"; // 动画时间
UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {320, 253}}"; // 键盘bounds
UIKeyboardCenterBeginUserInfoKey = "NSPoint: {160, 694.5}"; // 开始键盘的居中位置
UIKeyboardCenterEndUserInfoKey = "NSPoint: {160, 441.5}"; // 结束键盘的居中位置
UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 568}, {320, 253}}";// 键盘开始弹出的frame
UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 315}, {320, 253}}";// 退出键盘的frame
UIKeyboardIsLocalUserInfoKey = 1;

IOS开发——UI进阶篇(六)键盘处理

标签:

原文地址:http://www.cnblogs.com/chglog/p/4679053.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!