ios – 在编辑时将文本视图保持在键盘上方

我有一个动态高度的文本视图.当用户添加或删除文本时,文本视图的高度会发生变化.

我的问题是,当用户添加文本并且文本视图增长时,它会消失在键盘后面.当键盘出现时我已经成功移动了视图,因此文本视图从一开始就隐藏起来,但我似乎无法弄清楚如何在高度变化时将其保持在键盘上方.任何帮助深表感谢!

键盘出现和消失时移动视图的功能:

func keyboardWillShow(sender: NSNotification) {
    let info: NSDictionary = sender.userInfo!
    let value: NSValue = info.valueForKey(UIKeyboardFrameBeginUserInfoKey) as! NSValue
    let keyboardSize: CGSize = value.CGRectValue().size
    let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height + 20, 0.0)
    scrollView.contentInset = contentInsets

    var aRect: CGRect = self.view.frame
    aRect.size.height -= keyboardSize.height
    let activeTextFieldRect: CGRect? = activeItemRect()
    let activeTextFieldCentre: CGPoint? = CGPointMake(CGRectGetMidX(activeTextFieldRect!), CGRectGetMidY(activeTextFieldRect!))
    if (!CGRectContainsPoint(aRect, activeTextFieldCentre!)) {
        scrollView.scrollRectToVisible(activeTextFieldRect!, animated:true)
    }
}

func keyboardWillHide(sender: NSNotification) {
    let contentInsets: UIEdgeInsets = UIEdgeInsetsZero
    scrollView.contentInset = contentInsets
}

最佳答案 所以需要发生的是,只要光标的位置发生变化,如果它位于边界之外,则需要告知包含scrollView.我已经从链接改编了一个函数来调用这个.确保将scrollView替换为您的名字.

internal func scrollToCursorForTextView(textView: UITextView) {
    var cursorRect = textView.caretRectForPosition(textView.selectedTextRange!.start)
    cursorRect = scrollView.convertRect(cursorRect, fromView: textView)
    if !self.rectVisible(cursorRect) {
      cursorRect.size.height += 8
      scrollView.scrollRectToVisible(cursorRect, animated: true)
    }
}

internal func rectVisible(rect: CGRect) -> Bool {
    var visibleRect = CGRect()
    visibleRect.origin = scrollView.contentOffset
    visibleRect.origin.y += scrollView.contentInset.top
    visibleRect.size = scrollView.bounds.size
    visibleRect.size.height -= scrollView.contentInset.top + scrollView.contentInset.bottom
    return CGRectContainsRect(visibleRect, rect)
}

Swift 4更新

internal func scrollToCursorForTextView(textView: UITextView) {
    guard let startOfRange = textView.selectedTextRange?.start else { return }
    var cursorRect = textView.caretRect(for: startOfRange)
    cursorRect = scrollView.convert(cursorRect, from: textView)
    if !rectVisible(rect: cursorRect) {
        cursorRect.size.height += 8
        scrollView.scrollRectToVisible(cursorRect, animated: true)
    }
}

func rectVisible(rect: CGRect) -> Bool {
    var visibleRect = CGRect()
    visibleRect.origin = scrollView.contentOffset
    visibleRect.origin.y += scrollView.contentInset.top
    visibleRect.size = scrollView.bounds.size
    visibleRect.size.height -= scrollView.contentInset.top + scrollView.contentInset.bottom
    return visibleRect.contains(rect)
}
点赞