How to Send Multiple Buttons in Button.Addtarget Action? Swift3

Attach parameter to button.addTarget action in Swift

You cannot pass custom parameters in addTarget:.One alternative is set the tag property of button and do work based on the tag.

button.tag = 5
button.addTarget(self, action: "buttonClicked:",
forControlEvents: UIControlEvents.TouchUpInside)

Or for Swift 2.2 and greater:

button.tag = 5
button.addTarget(self,action:#selector(buttonClicked),
forControlEvents:.TouchUpInside)

Now do logic based on tag property

@objc func buttonClicked(sender:UIButton)
{
if(sender.tag == 5){

var abc = "argOne" //Do something for tag 5
}
print("hello")
}

Pass multiple parameters to addTarget

May be you can do something like this

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCellWithIdentifier("CartCell", forIndexPath:indexPath) as! CartTableViewCell
cell.buyButton.tag = (indexPath.section*100)+indexPath.row
cell.buyButton.addTarget(self, action: "btnBuy_Click:", forControlEvents: .TouchUpInside)
}

func btnBuy_Click(sender: UIButton) {
//Perform actions here
let section = sender.tag / 100
let row = sender.tag % 100
let indexPath = NSIndexPath(forRow: row, inSection: section)
self.buyButton(indexPath, 2, 3 ,4 , 5, 6)
}

Create tag value according to you'r requirement and maintaint it's integrity too.

Passing parameters to addTarget:action:forControlEvents

action:@selector(switchToNewsDetails:)

You do not pass parameters to switchToNewsDetails: method here. You just create a selector to make button able to call it when certain action occurs (touch up in your case). Controls can use 3 types of selectors to respond to actions, all of them have predefined meaning of their parameters:

  1. with no parameters

    action:@selector(switchToNewsDetails)
  2. with 1 parameter indicating the control that sends the message

    action:@selector(switchToNewsDetails:)
  3. With 2 parameters indicating the control that sends the message and the event that triggered the message:

    action:@selector(switchToNewsDetails:event:)

It is not clear what exactly you try to do, but considering you want to assign a specific details index to each button you can do the following:

  1. set a tag property to each button equal to required index
  2. in switchToNewsDetails: method you can obtain that index and open appropriate deatails:

    - (void)switchToNewsDetails:(UIButton*)sender{
    [self openDetails:sender.tag];
    // Or place opening logic right here
    }


Related Topics



Leave a reply



Submit