简体   繁体   中英

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

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..

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.

I used that code snippet with normal text with no issue, so I guess it is a problem about 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??

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!!)

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.

There are major problems with your code, by the way. In particular: If you are using constraints you must not use frame ! The constraints position and size the object; that is what they are for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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