简体   繁体   中英

Incorrect intrinsic size of attributed text in label

I have problem with attributed text in label that takes to much space at the bottom. When I was using not attributed one, sizing was ok, but now I have always bottom space - marked pink on the image . I tried changing value of height constraint (generated by iOS) in Reveal.app and when I make it even one point smaller than it is, text is truncated.

I need attributed label because I am making attributes from HTML string:

<p style=\"font-family: EncodeSans-Thin; font-size: 10.0; color: #1f2e3b;\">
    Od 2004 roku wspieramy organizacje biznesowe w rozwoju sztuki zarządzania projektami. 
    Nasza działalność opiera się na trzech filarach – 
    <span style=\"font-family: EncodeSans-Light\">
        doradztwie, realizacji projektów na zlecenie oraz szkoleniach.
    </span>
</p>

底层空间

Have you encountered such problem?

UPDATE:

I am using function below to produce NSAttributedString from HTML string (as a String extension).

func makeAttributesFromHTML() -> NSAttributedString {
    guard let htmlData = self.dataUsingEncoding(NSUTF8StringEncoding) else {
        return NSAttributedString()
    }

    do {
        let atributedString = try NSAttributedString(data: htmlData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding], documentAttributes: nil)

        return atributedString
    } catch {
        return NSAttributedString()
    }
}

I've definitely had this before. I find that once you've set the text on the label you then have to update it using

label.attributedText = foo;
[label setNeedsLayout]; // this line normally isn't required
[label layoutIfNeeded];

This should resize the label to the correct size. Failing that, I'm not entirely sure how your autolayout constraints are setup but you could manually calculate the new height of the label and set its height constraint based on that. This normally isn't necessary though.

Lastly, you might have trailing whitespace at the end of your text. Make sure to remove it if you don't want it.

I found out that removing <p> tags from the HTML content fixes the sizing. Which makes me think that it is sizeToFit method that fails to calculate the size correctly when it has to deal with paragraphs in attributed strings created from HTML .

I know that this is not the best solution but maybe you can replace <p> tags with <br> . This is the only fix I managed to find so far.

It is because <p> tags inherently adds new line at the end. One way to do it could be to use <div style = display: inline> this way it won't add new line

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