![](/img/trans.png)
[英]How to set the text field in UITextView to go up and down when the keyboard comes?
[英]How can I achieve automatic scrolling in my text view when text comes down to the keyboard level in Swift?
我知道当内容(文本)超过文本视图的默认高度时会自动滚动,但我希望文本视图为全屏,当内容进入键盘级别时,文本视图应自动滚动。 我给了一个GIF来帮助读者更好地理解。
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
}
}
斯威夫特5
也许这条线对你有用。
你应该在textViewDidChange
函数中使用这样的动画设置contentOffSet
:
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)
})
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.