当键盘出现iOS时向上滚动tableview行

Posted

技术标签:

【中文标题】当键盘出现iOS时向上滚动tableview行【英文标题】:Scroll tableview row up when keyboard appears iOS 【发布时间】:2016-11-15 10:53:05 【问题描述】:

当键盘出现时,我的应用程序的一些 ui 组件从底部隐藏,实际上它是 tableView's 最后一行。

我正在使用NSNotificationCenter 通知键盘何时出现和消失。

这是我的代码:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardOnScreen:) name:UIKeyboardDidShowNotification object:nil];

-(void)keyboardOnScreen:(NSNotification*)notification
    NSDictionary* info = [notification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    CGRect screen = self.view.frame;        
    screen.size.height -= kbSize.height;
    float HeightOfToolbar =_inputbar.frame.size.height; //TOOLBAR
    float yPoint = screen.size.height-HeightOfToolbar;
    CGPoint scrollPt = CGPointMake(0, yPoint);
    [_dataTable setContentOffset:scrollPt animated:YES];

但是,tableview 向上滚动但不在正确的行,即键盘上方的最后一行。 有时它会滚动到隐藏最后一行的倒数第二行,或者更多。 它与 scrollPt 值有关!

【问题讨论】:

如果您觉得可以,请使用tpkeyboardavoidingscrollview lib。 @vaibhav 有这么难吗.. 我应该使用 tpkeyboardavoidingscrollview?? 我在之前的评论中没有提到任何困难的地方。 如果您将 tableview 控制器与单元格一起使用,则上述一个将默认行为。 @Vinodh 会尝试你的建议 :) 【参考方案1】:

使用此方法出现键盘

- (void)keyboardWasShown:(NSNotification *)aNotification 
        NSDictionary* info = [aNotification userInfo];
        CGSize Size = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

        UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, Size.height - HeightOfToolbar, 0.0);//Set height according to key board height
        self.tableView.contentInset = contentInsets;
        self.tableView.scrollIndicatorInsets = contentInsets;
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        

隐藏键盘

 - (void)keyboardWasHidden:(NSNotification *)aNotification
    

    self.tableView.contentInset = UIEdgeInsetsZero;
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsZero;
    

【讨论】:

每次我关闭键盘,在执行 keyboardWasHidden 后,keyboardWasShown 都会被调用!! 你使用了滚动代理方法吗? 是的.. scrollViewDidScroll 和 scrollViewDidScrollToTop 我已经处理了在keyboardWasHidden 之后调用keyboardWasShown 方法。你能告诉我,为什么表格行在表格中向上滚动然后向下滚动到最后一行! 此方法在ScrollPosition:可以管理ScrollPosition顶行或底行

以上是关于当键盘出现iOS时向上滚动tableview行的主要内容,如果未能解决你的问题,请参考以下文章

关闭操作表时,ios tableview不会向上滚动

当键盘出现并启用滚动时,TextField 向上移动

当表格视图向上滚动时,表格视图第一部分(第 0 部分)没有向上移动

Facebook 和键盘动画管理

键盘出现多次时,滚动视图不会向上移动

tableview 中的两个 TextFields,都在滚动视图上,当键盘出现 iPhone 时消失