Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get label name from Button?

Tags:

ios

swift

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?

like image 808
Dharmesh Kheni Avatar asked Sep 27 '14 11:09

Dharmesh Kheni


People also ask

How do I get element labels?

Use the textContent property to get the text of a label element, e.g. const text = label. textContent . The textContent property will return the text content of the label and its descendants. If the element is empty, an empty string is returned.

Can a button have a label?

Yes, your button must have so form of text label associated with it.


1 Answers

If you are sure that titleLabel is not nil:

println(TheButton.titleLabel!.text) 

else

if let text = TheButton.titleLabel?.text {     println(text) } 
like image 128
Kirsteins Avatar answered Sep 28 '22 09:09

Kirsteins