简体   繁体   English

UITextView内容在增加高度的同时改变位置

[英]UITextView content changing position while increasing height

I am trying to change the height of a UITextView based on the size of its content using textViewDidChange delegate call. 我试图使用textViewDidChange委托调用基于其内容的大小更改UITextView的高度。 But text is pushed up a bit while the first line is entered and is corrected to old position when the next line is entered, This keeps on repeating for every alternate line added. 但是输入第一行时文本会被推高一点,并且在输入下一行时将文本更正为旧位置。对于添加的每个备用行,这将继续重复。

func textViewDidChange(textView: UITextView!) {
    var computedHeightDifference = textView.contentSize.height - textView.frame.size.height
    if(computedHeightDifference != 0){
        textView.frame.size.height = textView.contentSize.height
    }

}

I tried using textView.sizeToFit() instead of the complete block but the text view blinks when each line is added(Same behaviour can be noticed in the notes field while adding new contact in the Phone application. 我尝试使用textView.sizeToFit()而不是完整的块,但添加每一行时文本视图闪烁(在电话应用程序中添加新联系人时,可以在备注字段中注意到相同的行为。

I have uploaded the complete code on GitHub 我已经在GitHub上传了完整的代码 进入第一线同时添加另一行

You're not setting the height large enough. 你没有设置足够大的高度。 You need to account for the text container's inset. 您需要考虑文本容器的插入。

Do this: 做这个:

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
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM