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

iOS开发TextField根据键盘自适应位置

时间:2016-05-07 07:12:34      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

- (void)setNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
- (void)closeNotification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)keyboardWillChangeFrame:(NSNotification *)notification {
    
    NSDictionary *dict = [notification userInfo];
    // 键盘弹出和收回的时间
    CGFloat duration = [[dict objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    // 键盘初始时刻的frame
    CGRect beginKeyboardRect = [[dict objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    // 键盘停止后的frame
    CGRect endKeyboardRect = [[dict objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    // 相减为键盘高度
    CGFloat yOffset = endKeyboardRect.origin.y - beginKeyboardRect.origin.y;
    
    // 创建appDelegate单例对象
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    // 初始化一个数组,UIWindow的所有子视图
    NSArray *array = appDelegate.window.subviews;
    // 获取当前Controller的view视图
    UIView *view = appDelegate.window.subviews[array.count - 1];
    // textField相对于UIWindow的frame
    CGRect selfFrameFromUIWindow = [self convertRect:self.bounds toView:appDelegate.window];
    // textField底部距离屏幕底部的距离
    CGFloat bottomHeight = [UIScreen mainScreen].bounds.size.height - selfFrameFromUIWindow.origin.y - selfFrameFromUIWindow.size.height;
    
    
    // 初始化一个frame,大小为UIWindow的frame
    CGRect windowFrame = appDelegate.window.frame;
    // 把这个frame的y值增加或减少相应的高度(这里的40是textField底部和键盘顶部的距离)
    windowFrame.origin.y += yOffset + bottomHeight - 40;
    // 根据yOffset判断键盘是弹出还是收回
    if (yOffset < 0) {
        // 键盘弹出,改变当前Controller的view的frame
        [UIView animateWithDuration:duration animations:^{
            view.frame = windowFrame;
        }];
    } else {
        // 键盘收回,把view的frame恢复原状
        [UIView animateWithDuration:duration animations:^{
            view.frame = appDelegate.window.frame;
        }];
    }
}

iOS开发TextField根据键盘自适应位置

标签:

原文地址:http://blog.csdn.net/l2i2j2/article/details/51335428

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