Adding target to button to accessory View

617 Views Asked by At

I have created a button which I have assigned to my accessoryView. I get to see the created button, but when I press on it, nothing happens. Can anyone see what I'm doing wrong?

   let accessoryButton = UIButton(type: .roundedRect)
    accessoryButton.setTitle("message", for: .normal)
    accessoryButton.sizeToFit()

    accessoryButton.addTarget(self, action: #selector(goToMessaging(sender:)), for: UIControlEvents.touchUpInside)

    cell.accessoryView = accessoryButton as UIView



 @objc func goToMessaging(sender: UIButton){
    print("message him")
}
2

There are 2 best solutions below

3
CalebDavis On

Could it be because you are casting the button to a UIView?

accessoryButton as UIView

You could try adding a tap gesture recognizer to the accessoryView if it has to be a UIView.

0
user3325024 On

try this

@objc func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //let cell = ...
        cell.accessoryType = UITableViewCellAccessoryType.detailButton
        cell.tintColor = .red
}

func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {

        print("accessory Button Tapped = \(indexPath.row)")
}