Swift - How to get the value of a button when pressed?

I want to get the value of the button when it is pressed.

I tried this to print a 4 * 4 matrix by the given code -

func creation_of_btn()
{
var x_axis:CGFloat = 50.0
var y_axis:CGFloat = 50.0

for x in 1...4
{
  for y in  1...5
  {
       let btn_creat = UIButton.buttonWithType(UIButtonType.Custom) as UIButton!
       btn_creat.frame = CGRectMake(x_axis, y_axis, 100, 100)
       x_axis += 110.0
       btn_creat.backgroundColor = UIColor .redColor()

       btn_creat.font = UIFont .boldSystemFontOfSize(50)

       var myString = String(self.rand_creation(1, second: 9))
       btn_creat .setTitle(myString, forState: UIControlState.Normal)
       btn_creat.addTarget(self, action: "btnAction:", forControlEvents: UIControlEvents.TouchUpInside)
       self.view.addSubview(btn_creat)
   }

   x_axis = 50.0
   y_axis += 110.0
}
}

When the button is pressed, the code -

func btnAction (sender:UIButton!)
{
   println("pressed")
}

In the above code, I get the following output: enter image description here

Now, when I press button 1, I want to print the value of the button, which is 1.

+4
source share
3 answers

You get pressed UIButton as a parameter sender. This way you can read the text of the UIButton header.

println(sender.titleLabel.text)

Or, if the titleLabel of the button is different from the value, use the attribute tag. You can determine the value of a tag during the creation of UIButtons.

+4
source

- tag UIButton.

, :

btn_creat.tag = self.rand_creation(1, second: 9)
var myString = String(btn_creat.tag)

, , btnAction::

println(sender.tag)
+5

You have already set the name, so just return it.

func btnAction(sender: UIButton) {
    println(sender.currentTitle!)
}
0
source

Source: https://habr.com/ru/post/1544867/


All Articles