我正在尝试使用 textViewDidChange 委托(delegate)调用根据其内容的大小更改 UITextView 的高度。但是在输入第一行时文本会被向上推一点,并在输入下一行时将其更正到旧位置,这会在添加的每个备用行中不断重复。
func textViewDidChange(textView: UITextView!) {
var computedHeightDifference = textView.contentSize.height - textView.frame.size.height
if(computedHeightDifference != 0){
textView.frame.size.height = textView.contentSize.height
}
}
我尝试使用 textView.sizeToFit() 而不是完整的 block ,但是当添加每一行时 TextView 会闪烁(在电话中添加新联系人时,在注释字段中可以注意到相同的行为申请。
我已经在 GitHub 上上传了完整的代码
请您参考如下方法:
您没有将高度设置得足够大。您需要考虑文本容器的插图。
这样做:
func textViewDidChange(textView: UITextView!) {
var computedHeightDifference = textView.contentSize.height - (textView.frame.size.height + textView.textContainerInset.top + textView.textContainerInset.bottom)
if(computedHeightDifference != 0){
textView.frame.size.height = textView.contentSize.height + textView.textContainerInset.top + textView.textContainerInset.bottom
}
}
