美文网首页
iOS视图跟随键盘上移

iOS视图跟随键盘上移

作者: 东东隆东抢 | 来源:发表于2017-05-18 16:08 被阅读495次

自我mark一下。如下图所示:界面上有2个textField,当其成为第一响应者时弹出键盘且要求textField的父视图跟随键盘上移。另外要求时间标签上的时间实时显示。
实现原理:注册通知监听键盘的frame变化,从而改变textField父视图的bottom约束值。

示意图.gif
    UIKeyboardAnimationCurveUserInfoKey = 7;//动画效果
    UIKeyboardAnimationDurationUserInfoKey = "0.25";//键盘弹出动画时间
    UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
    UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
    UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
    UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";//键盘起始frame
    UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";//键盘弹出时frame
    UIKeyboardIsLocalUserInfoKey = 1;

 //1,注册通知,监听键盘frame变化
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
-(void)keyboardWillChangeFrame:(NSNotification*)notification{
    
    // NSLog(@"notification-info:%@",notification.userInfo);
    
    //获取键盘弹起时y值
    CGFloat keyboardY=[notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
    
    //改变底部约束
    self.bottomConstraint.constant=[UIScreen mainScreen].bounds.size.height-keyboardY;//bottomConstraint是textField的父视图距离self.View的底部距离
    //获取键盘弹起时间
    CGFloat duration=[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration: duration animations:^{
        [self.view layoutIfNeeded];
    }];

}

记得要在dealloc方法里移除通知:

    //移除通知
    [[NSNotificationCenter defaultCenter]removeObserver:self];

时间标签实时显示

 //创建定时器,刷新时间
    __weak KeyboardViewController *weakSelf=self;
    _timer=[NSTimer timerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        KeyboardViewController *strongSelf=weakSelf;
        [strongSelf updateTime];//使用strong是为了保证实例持续存活
    }];
-(void)updateTime{
    //设置时间label
    NSDate *currentDate = [NSDate date];//获取当前时间、日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    self.timeLabel.text=dateString;
}

Demo下载地址

相关文章

网友评论

      本文标题:iOS视图跟随键盘上移

      本文链接:https://www.haomeiwen.com/subject/nfbsxxtx.html