简体   繁体   English

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

[英]Swift button callback in tableview cell not working

I want to have a UIButton inside my TableViewCell and I tried it with a closure but it is not doing anything:我想在我的TableViewCell里面有一个UIButton并且我用一个closure尝试了它,但它没有做任何事情:

Cell : 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
}

What am I missing here?我在这里缺少什么?

I found the issue.. I called self.addSubView(favouriteButton so the contentView actually covered the button. Simply fixed it by calling this:我发现了这个问题..我打电话给self.addSubView(favouriteButton所以contentView实际上覆盖了按钮。只需通过调用它来修复它:

contentView.addSubview(favouriteButton)

Thanks for all the help!感谢所有的帮助!

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


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

and

cell.favouriteButtonTappedCallBack

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM