当文本下降到Swift中的键盘级别时,如何在文本视图中实现自动滚动?

时间:2019-06-25 05:19:11

标签: ios swift

我知道当内容(文本)超过文本视图的默认高度时会自动滚动,但是我希望文本视图为全屏,并且当内容达到键盘级别时,文本视图应该滚动自动。我提供了一个GIF,以帮助读者更好地理解。

Notes on IOS

class StartStoryPopUp: UIViewController, UITextViewDelegate {
    // Setup text view
    func setupTextView() {

        textViewOne.textColor = .black
        textViewOne.backgroundColor = baseColor
        // Add some padding to the text insde the text view
        textViewOne.textContainerInset = UIEdgeInsets(top: 15, left: 10, bottom: 15, right: 10)
        textViewOne.font = UIFont(name: "PatrickHand-Regular", size: 25)
        textViewOne.layer.cornerRadius = 25

        popUp.addSubview(textViewOne)
        addTextViewConstraints()
    }

    // Add the constraints to the 'start story' text view
    func addTextViewConstraints() {

        textViewOne.translatesAutoresizingMaskIntoConstraints = false
        textViewOne.leadingAnchor.constraint(equalTo: popUp.leadingAnchor, constant: 3).isActive = true
        textViewOne.trailingAnchor.constraint(equalTo: popUp.trailingAnchor, constant: -3).isActive = true
        textViewOne.topAnchor.constraint(equalTo: popUp.topAnchor, constant: 3).isActive = true
        textViewOne.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -30).isActive = true
    }
}

1 个答案:

答案 0 :(得分:6)

快速5

也许这行对你有用。

您应使用以下动画在contentOffSet函数中设置textViewDidChange

func textViewDidChange(_ textView: UITextView) {

    let line = textView.caretRect(for: (textView.selectedTextRange?.start)!)
    let overFlow = line.origin.y + line.size.height - (textView.contentOffset.y + textView.bounds.size.height - textView.contentInset.bottom - textView.contentInset.top)

    if 0 < overFlow {

        var offSet = textView.contentOffset
        offSet.y += (overFlow + 7)

        UIView.animate(withDuration: 0.3, animations: {
            textView.setContentOffset(offSet, animated: true)
        })
    }
}