繁体   English   中英

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

[英]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
}

我在这里缺少什么?

我发现了这个问题..我打电话给self.addSubView(favouriteButton所以contentView实际上覆盖了按钮。只需通过调用它来修复它:

contentView.addSubview(favouriteButton)

感谢所有的帮助!

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


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

cell.favouriteButtonTappedCallBack

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

暂无
暂无

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

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