How to check if UILabel has attributedText or normal text programmatically?
Inspired by @lukas-o I have written an extension on UILabel
that determines if it contains an attributedText
or not. In fact if the NSAttributedString
does not contain any attributes, this computed property will evaluate it to not be attributed.
extension UILabel {
var isAttributed: Bool {
guard let attributedText = attributedText else { return false }
let range = NSMakeRange(0, attributedText.length)
var allAttributes = [Dictionary<String, Any>]()
attributedText.enumerateAttributes(in: range, options: []) { attributes, _, _ in
allAttributes.append(attributes)
}
return allAttributes.count > 1
}
}
From the apple docs:
This property is nil by default. Assigning a new value to this property also replaces the value of the text property with the same string data, albeit without any formatting information. In addition, assigning a new a value updates the values in the font, textColor, and other style-related properties so that they reflect the style information starting at location 0 in the attributed string.
You are right, it's not possible to find that out checking one or the other for nil. One way you could know that the text is attributed would be to use something like:
NSMutableArray *strAttrs = [NSMutableArray new];
NSMutableArray *strRanges = [NSMutableArray new];
[label.attributedText enumerateAttributesInRange:NSMakeRange(0, label.attributedText.length) options:0 usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
[strAttrs addObject:attrs];
[strRanges addObject:[NSValue valueWithRange:(range)]];
}];
This way you could get see whether more than one attribute is there. You could also compare the attributes whether they match your standard attributes and assume that the text property has been set only in this case.