美文网首页
iOS之TextField随键盘显示而上移

iOS之TextField随键盘显示而上移

作者: 张大普奔 | 来源:发表于2017-06-27 10:16 被阅读28次
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidShow:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidHide:) name:UIKeyboardDidHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
}

- (void)keyBoardDidShow:(NSNotification *)notif {
    NSLog(@"===键盘显示====");
    if (keyboardDidShow) return;
    //获取键盘大小
    NSDictionary *info = [notif userInfo];
    NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [aValue CGRectValue].size;
    //注意:系统键盘有两个不同的高度(216和258),为了保持正常显示,键盘高度取258
    if (keyboardSize.height == 216) {
        keyboardSize.height = 258;
    }else{
        keyboardSize.height = 258;
    }
    //重置scrollview的frame
    CGRect viewFrame = self.scrollView.frame;
    viewFrame.size.height -= keyboardSize.height+44;
    self.scrollView.frame = viewFrame;
    
    //滚动到当前控件
    CGRect textfieldRect = [self.nameTextField frame];
    [self.scrollView scrollRectToVisible:textfieldRect animated:YES];
    keyboardDidShow = YES;
}

- (void)keyBoardDidHide:(NSNotification *)notif {
    NSLog(@"====键盘隐藏====");
    NSDictionary *info = [notif userInfo];
    NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [aValue CGRectValue].size;
    CGRect viewFrame = self.scrollView.frame;
    viewFrame.size.height += keyboardSize.height+44;
    self.scrollView.frame = viewFrame;
    if (!keyboardDidShow) {
        return;
    }
    keyboardDidShow = NO;
}

相关文章

网友评论

      本文标题:iOS之TextField随键盘显示而上移

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