user3591436
user3591436

Reputation: 161

Sender tag is always same data (wrong index?)

I have the following code for cell button:

    cell.buttonViewLink.addTarget(self, action: "buttonViewLinkAction:", forControlEvents: UIControlEvents.TouchUpInside)
    cell.buttonViewLink.tag = indexPath.item

So when I tap buttonViewLinkAction I get the correct name/image printed in NSLog, no matter which cell is tapped, it's always the correct data. This works great and creates another button:

    //get buttonViewLinkAction and copy to pasteboard
@IBAction func buttonViewLinkAction(sender: UIButton) {
    print("buttonViewLinkAction tapped")
    let face = self.faces[sender.tag]
    if let imageNAME: String = String(face.name){
        print(imageNAME .uppercaseString)
    }
    if let imageURL = NSURL(string:face.image) {
        print(imageURL)
    }

    UIPasteboard.generalPasteboard().string = face.directLink

    let alertView = SCLAlertView()
    alertView.addButton("Add [img] tags", target:self, selector:Selector("imgtagAction:"))
    alertView.showSuccess((face.name), subTitle: "Image link copied to clipboard")

}

But when I tap imgtagAction, I always get the data from cell 1.

    //get imgtagAction click
func imgtagAction(sender: UIButton!) {
    print("imgtagAction tapped")
    let face = self.faces[sender.tag]

    if let imageNAME: String = String(face.name){
        print(imageNAME .uppercaseString)
    }
    if let imageURL = NSURL(string:face.image) {
        print(imageURL)
    }
    UIPasteboard.generalPasteboard().string = "[img]" + face.directLink + "[/img]"
}

What am I doing wrong?

Upvotes: 0

Views: 187

Answers (1)

Nirav D
Nirav D

Reputation: 72410

As rmaaddy commented you haven't set tag with your button and I think it is may be not possible to set tag to that custom AlertView button action, So I think you need to declare one Int instance property and set its value inside buttonViewLinkAction method and then use that instance inside imgtagAction method like this.

var selectedItem = 0

Now set selectedItem value inside buttonViewLinkAction method.

@IBAction func buttonViewLinkAction(sender: UIButton) {
    self.selectedItem = sender.tag
    //Your other code
}

Now use this selectedItem inside imgtagAction method.

func imgtagAction(sender: UIButton!) {
    let face = self.faces[selectedItem]
}

Upvotes: 1

Related Questions