【发布时间】:2021-05-31 06:13:15
【问题描述】:
我有一个表格视图单元格,其中包含一个用于显示警报表的特定按钮。 我了解到按钮本身不能在表格视图单元格内按下。它必须从视图控制器中调用。 所以我添加了一个回调闭包,如下所示:
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?()
}
我怀疑这可能是表格视图单元格注册的问题。如果不是这样,请告诉我。在视图控制器中我这样做了:
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
}
}
所以主要问题是,为什么按钮不起作用?它甚至不打印“菜单”
感谢您的所有回答
【问题讨论】:
-
lazy var menuButton永远不会被初始化,因为您永远不会引用menuButton或将其添加为子视图 -
为了防止强引用,你应该使用
cell.callback = { [weak self] in而不是cell.callback = { -
我没有看到您将
menuButton作为子视图添加到单元格中?你在哪里做的? -
@aheze 实际初始化并添加到视图中。我只是跳过了那部分以节省问题中的空间
-
@Sweeper 抱歉,我只是跳过了这个以节省问题中的空间。我现在编辑它。请看一下
标签: ios swift uitableview closures uialertcontroller