Search code examples
iosswiftuitableviewclosuresuialertcontroller

Callback closure function not working in cell


I have a tableview cell which contains a specific button for showing alert sheet. I've learned that button itself can't be pressed inside of table view cell. It must be called from a view controller. So I`ve added a callback closure like so:

class FeedViewCell: UITableViewCell {

    var callback : (() -> ())?
    static let reuseIdentifier: String = "FeedTableViewCell" 

    lazy var menuButton: UIButton = {
        let btn = UIButton()
        btn.isUserInteractionEnabled = true
        btn.addTarget(self, action: #selector(menuTapped), for: .touchUpInside)
        return btn
    }()

 override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        addSubview(menuButton)

        }

    @objc func menuTapped() {
       print("menu tapped")
       callback?()
    }

I suspect it might be a problem with table view cell registration.. Pls let me know if that's not it. And in the view controller I did this:

class FeedViewController: UIViewController {
// some code...

  tableView.register(FeedViewCell.self, forCellReuseIdentifier: FeedViewCell.reuseIdentifier)

}

extension FeedViewController: UITableViewDelegate, UITableViewDataSource {    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: FeedViewCell.reuseIdentifier, for: indexPath) as! FeedViewCell
        cell.callback = {
            
            print("menu")
            let actionSheet = UIAlertController(title: "", message: "", preferredStyle: .actionSheet)
            
            actionSheet.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: { action in
                print("tap dismiss")
            }))
            
            actionSheet.addAction(UIAlertAction(title: "Follow", style: .default, handler: { action in
                print("tap follow")
            }))
            
            self.present(actionSheet, animated: true, completion: nil)
        }
        return cell
    }
}

So the main question is, why is the button not working? It doesn't even print "menu"

Thank you for all of your answers


Solution

  • This line is wrong.

    addSubview(menuButton)
    

    Instead:

    contentView.addSubview(menuButton)