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

- (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;
        }];
    }
}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值