Search code examples
swiftuilabel

In Swift, how do you retrieve the length of a UILabel?


I am trying to determine how many characters are in a UILabel so I can call numberOfLines when necessary.

I remember in Obj-C, I was able to able to access length on a UILabel's text property like so:

if (self.label.text.length >= 12)
    // Do something

How can I achieve the same result in Swift?


Solution

  • var myLabel = UILabel()
    // ...
    var numChars = myLabel.text?.characters.count ?? 0 // 0
    myLabel.text = "Foo bar"
    numChars = myLabel.text?.characters.count ?? 0     // 7