Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if UILabel has attributedText or normal text programmatically?

Is there any way to tell if UILabel has its text set using label.attributedText or label.text property?

The problem is when you set attributedText, text is also updated and vice versa, so it is not possible to check these properties for nil.

like image 968
Pavel Alexeev Avatar asked Apr 03 '15 18:04

Pavel Alexeev


People also ask

How do you check if a label is truncated?

You are dividing width by height and if it is bigger than number of line (which might very well be 0) you are saying label is truncated.

What is attributedText?

The styled text that the text view displays.

Is UILabel a view?

A view that displays one or more lines of informational text.


1 Answers

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
    }
} 
like image 166
Sajjon Avatar answered Sep 23 '22 11:09

Sajjon