Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

How to get label name from Button?

I am new in Swift and I am making a simple calculator where I wan't to detect a button which was pressed and my code is below.

 @IBAction func ButtonTapped(TheButton : UIButton){

    println(TheButton.titleLabel.text)
}

But It Shows me error like "UILabel? Does not have a member a named text"

and it tell me to modify code like this

println(TheButton.titleLabel?.text)

This Prints Optional("1") (1 is my button name)

So anybody can help me why this is happend to me and how can I print my button name without Optional?

Upvotes: 38

Views: 60480

Answers (5)

Amit Baderia
Amit Baderia

Reputation: 4882

Swift 5: I found this much cleaner

@IBAction func ButtonTapped(_ sender : UIButton){       
    guard let btnTxt = sender.titleLabel!.text else{
            return
    }

    print(btnTxt)  

    // now you can make use of this variable
    if btnTxt == "something" {
        .......
    }

}

Upvotes: 0

Sadiq Qasmi
Sadiq Qasmi

Reputation: 81

for Swift 5 There are many ways to do this but the easiest is just what I mentioned below:

@IBAction func keyPressed(_ sender:UIButton){
  print(sender.currentTitle!)
}

Upvotes: 1

Horatio
Horatio

Reputation: 1861

The top answer no longer works. Here is the corrected version for Swift 2.2:

If you are sure that titleLabel is not nil:

print(TheButton.titleLabel!.text!)

If you are not:

if let text = TheButton.titleLabel?.text {
    print(text)
}

Upvotes: 6

Andrew K
Andrew K

Reputation: 1599

More simply, you could just do:

let titleValueString = TheButton.currentTitle!

If the button's title is not nil, the exclamation point (!) will implicitly unwrap the optional (currentTitle without the exclamation point) and you will have a string value for the title of the button in your constant, titleValueString

Upvotes: 18

Kirsteins
Kirsteins

Reputation: 27335

If you are sure that titleLabel is not nil:

println(TheButton.titleLabel!.text)

else

if let text = TheButton.titleLabel?.text {
    println(text)
}

Upvotes: 57

Related Questions