简体   繁体   English

带有归因文本的textview的高度有时在iOS中是错误的

[英]The height of textview with attributed text is wrong sometimes in iOS

I'm forcing the height constraint of my textview with the following code 我用下面的代码强加我的textview的高度限制

func setHeightConstraint(textView: UITextView) {
    textView.sizeToFit()
    textView.layoutIfNeeded()

    var newFrame:CGRect=textView.frame
    newFrame.size.height=textView.contentSize.height
    textView.frame=newFrame
    println(textView.contentSize.height)
    textViewHeightConstraints.constant=textView.contentSize.height
}

My text view contains attributedText with links, bold, italic and so on.. 我的文本视图包含带有链接,粗体,斜体等的attributedText。

It works well sometimes, but does not on other times. 有时效果很好,但其他时候却不行。

I figured by printing textView.contentSize.height, that textView.contentSize.height is sometimes much smaller than it should be. 通过打印textView.contentSize.height,我发现textView.contentSize.height有时比实际值要小得多。

I used that code snippet with normal text with no issue, so I guess it is a problem about attributedText. 我将该代码段与普通文本一起使用没有问题,因此我认为这是关于attributedText的问题。

I tried googling and tried this and that code with no luck. 我尝试了谷歌搜索,并没有运气地尝试了该代码。

How should I measure the correct height of the textView when it contains attributedText?? 当textView包含attributedText时,应如何测量正确的高度?

Any help will be appreciated. 任何帮助将不胜感激。

Thanks in advance! 提前致谢!

(I can read Object-C code also though I prefer swift, so Object-C answer is appreciated as well!!) (尽管我更喜欢快速,但我也可以阅读Object-C代码,因此Object-C的回答也很受欢迎!)

It sounds like you are trying to make a text view whose height can be adjusted to fit its contents. 听起来您正在尝试制作一个文本视图,其高度可以调整以适合其内容。 This is how I do it: 这是我的方法:

func adjustHeight() {
    let sz = self.tv.sizeThatFits(CGSizeMake(self.tv.bounds.width, 10000))
    self.heightConstraint.constant = ceil(sz.height)
}

In that code, self.tv is the text view and self.heightConstraint is the internal constraint that sets its height. 在该代码中, self.tv是文本视图,而self.heightConstraint是设置其高度的内部约束。

There are major problems with your code, by the way. 顺便说一句,您的代码存在主要问题。 In particular: If you are using constraints you must not use frame ! 特别是:如果使用约束,则不得使用frame The constraints position and size the object; 约束对象的位置和大小; that is what they are for. 这就是他们的目的。

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

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