stackerleet
stackerleet

Reputation: 518

Why is the sender.tag always zero?

I have an array of buttons and when I add the action the sender.tag is always zero. How do I fix this? Below is my attempt to do this. When a button is clicked I am trying to get the image and name in another array to pass to the next view controller. The problem is that the sender.tag is always zero.

var userbutton = [UIButton]()
var upimage = [UIImage]()
var usernamearray = [String]()

for (index, users) in upimage.enumerate(){

        var userbutton = UIButton()
        userbutton.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
        userbutton.frame = CGRectMake(100, 100, 50, 50)
        userbutton.layer.cornerRadius = userbutton.frame.size.width/2
        userbutton.clipsToBounds = true
        userbutton.setImage(users, forState: .Normal)
}

func buttonAction(sender: UIButton) {
   let index = sender.tag
      self.dicSelected = ["text" : usernamearray[index] , "image" :  upimage[index]]

   print("index\(index)")

    self.selectedData.text = usernamearray[index] as? String
    self.selectedData.image = upimage[index] as? UIImage

    self.performSegueWithIdentifier("nearmeprofile", sender: dicSelected)

}

Upvotes: 1

Views: 1688

Answers (2)

Nicolas Miari
Nicolas Miari

Reputation: 16256

Like others said, you never set the tag property of any of your buttons, so they are all at the default value of 0.

Try this:

let tagBaseValue = 1000 // Custom value

for (index, users) in upimage.enumerate(){

    let tag = tagBaseValue + index

    var userbutton = UIButton()
    userbutton.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
    userbutton.frame = CGRectMake(100, 100, 50, 50)
    userbutton.layer.cornerRadius = userbutton.frame.size.width/2
    userbutton.clipsToBounds = true
    userbutton.setImage(users, forState: .Normal)

    userButton.tag = tag // <-- ADD THIS LINE!!!
}

EDITED: Made custom button tags start at a high value, different from zero, in order to distinguish from buttons without a custom tag value set (following suggestion by @rmaddy in the comments of @VirajPadsala's answer).

Upvotes: 3

Viraj Padsala
Viraj Padsala

Reputation: 1398

Just use last line code to get different tag for all your UIButton.

for (index, users) in upimage.enumerate(){

    var userbutton = UIButton()
    userbutton.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
    userbutton.frame = CGRectMake(100, 100, 50, 50)
    userbutton.layer.cornerRadius = userbutton.frame.size.width/2
    userbutton.clipsToBounds = true
    userbutton.setImage(users, forState: .Normal)
    userbutton.tag=index;  // <-- ADD this Line in your code.
}

Upvotes: 3

Related Questions