Pangu
Pangu

Reputation: 3819

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?

Upvotes: 0

Views: 3192

Answers (2)

Bran
Bran

Reputation: 11

based on @dfrib answer above, here is the update for Swift 5

var myLabel = UILabel()
myLabel.text = "character"
let totalCharacter = myLabel.text?.count ?? 0

print("total character: \(totalCharacter)"
// total character: 9

Upvotes: 1

dfrib
dfrib

Reputation: 73196

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

Upvotes: 3

Related Questions