【问题标题】:Callback closure function not working in cell回调闭包函数在单元格中不起作用
【发布时间】: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


【解决方案1】:

这一行是错误的。

addSubview(menuButton)

改为:

contentView.addSubview(menuButton)

【讨论】:

    【解决方案2】:

    尝试将按钮添加到单元格的内容视图中,如下所示: self.contentView.addSubview(self.menuButton)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      • 2018-06-29
      • 1970-01-01
      • 2013-03-18
      • 1970-01-01
      • 1970-01-01
      • 2012-10-01
      相关资源
      最近更新 更多