Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current Title of a button in Swift 3.0 , ios using sender.titleForState(.Normal)!

I tried to get the title of a button in swift like below.

@IBAction func buttonAction(_ sender: Any) {
  let buttonTitle = sender.titleForState(.Normal)!
}

but it didn't work,even it doesn't give any hint when we press . after the sender.

so what is the correct way of doing this in swift 3.0

Or else if we create an IBOutlet and then we use its currentTitle, it works fine like below. Why we cannot get it with sender. for above

@IBOutlet var thebutton: UIButton!

@IBAction func buttonAction(_ sender: Any) {
  let buttonTitle = thebutton.currentTitle!
  print(buttonTitle)
}
like image 848
Chanaka Anuradh Caldera Avatar asked Oct 16 '16 18:10

Chanaka Anuradh Caldera


2 Answers

Because parameter sender is in type Any instead of UIButton. Change the method signature to:

@IBAction func buttonAction(_ sender: UIButton) {
  if let buttonTitle = sender.title(for: .normal) {
    print(buttonTitle)
  }
}

and you should be good to go.

like image 136
Ozgur Vatansever Avatar answered Sep 27 '22 23:09

Ozgur Vatansever


To get the title of the button regardless of its current state in swift 3.0 try using this:

    @IBAction func buttonPressed(_ sender:UIButton){
       let buttonTitle = sender.titleLabel?.text
       print("\(String(describing: buttonTitle)")
    }

This will return the title for the state, based on the state that the button is current in.

like image 36
ZaneMan Avatar answered Sep 28 '22 00:09

ZaneMan