Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3.0 TableView Cell Button

I have set up a button on the tableview cell and I am wondering how I can manipulate it. Namely, I am interested in changing the name title of the button and add another target (different capabilities of the button) to when the button is clicked. My thinking is that this needs to be added into the buttonClicked func, but I am not sure how to reference the specific cellForRow that was clicked. Perhaps a conditional can be used to in cellForRow that determines what the button title is? I am not too sure what the best way to go about this is.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = guestTableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) 

    let button : UIButton = UIButton(type:UIButtonType.custom) as UIButton

    button.frame = CGRect(origin: CGPoint(x: 200,y :60), size: CGSize(width: 100, height: 24))
    let cellHeight: CGFloat = 44.0
    button.center = CGPoint(x: view.bounds.width / (4/3), y: cellHeight / 2.0)


    button.setTitleColor(.blue, for: .normal)
    button.addTarget(self, action: #selector(buttonClicked), for: UIControlEvents.touchUpInside)
    button.setTitle("Add", for: UIControlState.normal)

    cell.addSubview(button)


    return cell
}

func buttonClicked(sender : UIButton!) {
    print("Added!")


}
like image 857
Kevin Avatar asked May 16 '26 17:05

Kevin


1 Answers

For Swift 4 and Swift 5

Find "indexPath.row" and "indexPath.section"

//Add target on button in "cellForRowAt"

cell.myBtn.addTarget(self, action: #selector(self.btnAction(_:)), for: .touchUpInside)

// Add function

func btnAction(_ sender: UIButton) {
    
    let point = sender.convert(CGPoint.zero, to: yourTableView as UIView)
    let indexPath: IndexPath! = yourTableView.indexPathForRow(at: point)
    
    print("row is = \(indexPath.row) && section is = \(indexPath.section)")
}
like image 174
Bijender Singh Shekhawat Avatar answered May 19 '26 07:05

Bijender Singh Shekhawat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!