Swift tableview 单元格中的按钮回调不起作用

Swift button callback in tableview cell not working

我想在我的 TableViewCell 里放一个 UIButton,我用 closure 试了一下,但它什么也没做:

Cell:

let favouriteButton: UIButton = {
    let v = UIButton()
    v.setImage(UIImage(systemName: "star"), for: .normal)
    v.setImageTintColor(.darkCustom)
    v.addTarget(self, action: #selector(favouriteButtonTapped), for: .touchUpInside)
    v.imageView?.contentMode = .scaleAspectFit
    v.contentHorizontalAlignment = .fill
    v.contentVerticalAlignment = .fill
    v.translatesAutoresizingMaskIntoConstraints = false
    return v
}()

var favouriteButtonTappedCallback: (() -> ())?

@objc func favouriteButtonTapped() {
    self.favouriteButtonTappedCallback?()
}

CellForRowAt:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: SearchBarCell.reuseID) as! SearchBarCell
    
    cell.favouriteButtonTappedCallback = {
        print("tapped")
    }
    return cell
}

我在这里错过了什么?

typealias FavouriteButtonTappedCallback = () -> Void   
var favouriteButtonTappedCallBack = FavouriteButtonTappedCallBack?


 if let tappedClosure = self.favouriteButtonTappedCallback {
            tappedClosure()
        }

cell.favouriteButtonTappedCallBack

检查所有视图层次结构并为所有视图启用用户交互,这可能是主要嫌疑人。

我发现了问题。我调用了 self.addSubView(favouriteButton,所以 contentView 实际上覆盖了按钮。简单地通过调用这个来修复它:

contentView.addSubview(favouriteButton)

感谢大家的帮助!