How to get click event UIbutton on tableView cell?

2019-08-31 05:14发布

问题:

I have taken UIbutton on TableViewCell, but when I click on a row, only the row get clicked, but I want to click only the button on that row.

How is this possible?

回答1:

In the CellForRowatindexPath define tag for button and also set target to handler the event

button.tag=indexPath.row;
button.addTarget(self, action: "buttonHandler:", forControlEvents: UIControlEvents.TouchUpInside)

*************
func buttonHandler(sender:UIButton!)
{
    if(sender.tag==0){
         println("Button at row 0")
    }
    else if(sender.tag==1){
       println("Button at row 1")
    }
}


回答2:

you set click event for cell Button try this way

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {   
 cell.yourButton.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
}


func buttonClicked(sender:UIButton!)
{
    println("Button tapped")
}


回答3:

First do one thing

cell.selectionStyle = UITableViewCellSelectionStyleNone;
 // This will disable the selection highlighting.

Then create IBOutlet of your button in Cell class (Don't create the IBAction yet!!!)

Then in your CellForRowatindexPath create the action of button like this

  button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)

then create the button action Function

func buttonAction(sender:UIButton!)
{
    println("Button tapped")
}

Check it. Hope it helps!!!!