How to get click event UIbutton on tableView cell?

2019-08-31 04:47发布

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?

3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-08-31 05:21

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")
    }
}
查看更多
姐就是有狂的资本
3楼-- · 2019-08-31 05:21

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!!!!

查看更多
走好不送
4楼-- · 2019-08-31 05:22

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")
}
查看更多
登录 后发表回答