Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - How to get the button value, when it is being pressed?

Tags:

swift

i want to get button value, when it get pressed.

I've tried this to print a 4*4 Matrix by 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 button is pressed, the code is -

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

By above code, I'm getting the following output- enter image description here

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

like image 704
ChenSmile Avatar asked Jun 17 '14 08:06

ChenSmile


1 Answers

One way to achieve what you want is to use the tag property of UIButton.

Add this line to the loop that creates the button:

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

Now that your tag is set to the button's number, you can print it in the btnAction: code:

println(sender.tag)
like image 183
Sergey Kalinichenko Avatar answered Sep 25 '22 21:09

Sergey Kalinichenko