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

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

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) }

回答1:

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.



回答2:

Since Swift 3.0, it changed from

sender.titleForState(.Normal)! >> sender.title(for : .normal)!

Change Any to AnyObject.

@IBAction func buttonPressed(_ sender: AnyObject) {   let title = sender.title(for: .normal)!   print("\(title) button pressed") }


回答3:

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.



回答4:

  @IBAction func btnNextTapped(_ sender: Any) {     let title = (sender as AnyObject).title(for: .normal)!   }

Swift4.0



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!