I have a UILabel
in a table cell, I have set its font in the interface builder. Now when the cell is being displayed I take and HTML string and convert it to an NSAttributedString
where I use the label's font type and size and use it as the default font for that HTML text.
The problem is that every time the cell is reused its label's font doubles its size e.g. starts at 17 points, then is 34, 68 up to millions...
I never set anything into the font property of the label, so why it could be changing?
This my String extension for for formatting it into NSAttributeString:
public func getHtml2AttributedString(font: UIFont) -> NSAttributedString? {
let modifiedString = "<style>body{font-family: '\(font.fontName)'; font-size:\(font.pointSize)px; margin:0; padding:0;}</style>\(self)";
guard let data = modifiedString.data(using: .utf8) else {
return nil
}
do {
return try NSAttributedString(data: data,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue],
documentAttributes: nil)
}
catch {
print(error)
return nil
}
}
EDIT: Just discovered that the font does not always doubles its size but it could enlarge it by just few points. And can also change weight e.g. from normal to bold.
The cellForRowAt
method just dequeues a cell and returns it and the willDisplay
method does something like this (Tt goes through several layers of abstractions but this is the only code that touches UI elements. The cell has just one label, nothing more):
label.attributedText = htmlString?.getHtml2AttributedString(font: label.font)
In the end this is a "feature" of the UILabel
, that after setting the attributedText property it automagically changes its font property based on the attributedText's properties. More can be found in another SO question.