Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

titleLabel.text vs currentTitle in Swift

Tags:

swift

uibutton

I am trying to make a simple calculator with Swift. I want to get the "text" on the buttons I created. The instructor in the tutorial is using a property:

@IBAction func appendDigit(sender: UIButton) {
    let digit = sender.currentTitle
}

The question is, if I did this:

@IBAction func appendDigit(sender: UIButton) {
    let digit = sender.titleLabel.text
}

What's the difference? Will they yield the same results? If so, how does one know when to use which?

like image 416
Ray Tso Avatar asked Oct 24 '25 15:10

Ray Tso


1 Answers

titleLabel.text is mainly using to configure the text of the button(for each state)

currentTitle is read only. This is mainly using to get the title that is currently displayed.

You can't set this property because this set automatically whenever the button state changes. You can use currentTitle to get the title string associated with the button instead of using titleLabel.text because currentTitle property is set automatically whenever the button state changes.

like image 94
Shamsudheen TK Avatar answered Oct 27 '25 06:10

Shamsudheen TK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!