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