在显示键盘时,在UITableView中保持重点UITextView的可见性



我正在动态构建一个表单,该表单为每个UITableViewCell具有各种类型的UI元素。

有一个UITableViewCell包含UITextView,我希望在显示键盘时能够保持可见性。我研究过其他类似的问题,但一直无法找到解决方案。

我写了Swift版本的推荐:苹果的管理键盘

它不起作用有两个原因。1.)键盘通知在TextViewWillBeginEditing之前触发。2.)UITextView的帧与作为UITableViewCell的超视图相关,因此检查是错误的。

这是我当前的代码:

func adjustTableViewForKeyboard(notification: NSNotification) {
        let userInfo = notification.userInfo!
        let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let keyboardViewEndFrame = view.convertRect(keyboardScreenEndFrame, fromView: view.window)
        if notification.name == UIKeyboardWillHideNotification {
            self.tableView.contentInset = UIEdgeInsetsZero
        } else {
            self.tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardViewEndFrame.height, right: 0)
            rect = self.view.frame;
            rect!.size.height -= keyboardViewEndFrame.height
        }
        self.tableView.scrollIndicatorInsets = self.tableView.contentInset
    }

func textViewDidBeginEditing(textView: UITextView) {
        self.activeTextView = textView;
        if(activeTextView != nil){
            // This check does NOT work due to the TextView's superview is the cell.
            if(!CGRectContainsPoint(rect!, (activeTextView?.frame.origin)!)){
                self.tableView.scrollRectToVisible((activeTextView?.frame)!, animated: true)
            }
        }
    }

这可以滚动到所有单元格,但我也想确保UITextView不会被键盘隐藏。

您可以使用响应程序链来解决此问题。在通知处理程序中,尝试在文本视图中调用isFirstResponder();如果它返回true,那么您可以从那里调用表视图滚动代码。

我在构建一个(尽管是静态单元格)表单时遇到了类似的问题,我能够使用scrollToRowAtIndexPath方法更新表视图的行位置,以使文本视图保持在屏幕上。

func textViewDidBeginEditing(textView: UITextView) {
    if textView == notesTextView {
        tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 3), atScrollPosition: .Top, animated: true)
    }
}

它确实需要了解索引路径节/行和文本视图引用(如果是倍数),但可能有用吗?

scrollRectToVisible也应该工作,但听起来您必须首先使用convertRect:toView或类似的方法将文本视图的框架转换为滚动视图的坐标系。

希望这有帮助——干杯。

最新更新