【问题标题】:How to referencing a callback function on Swift iOS?如何在 Swift iOS 上引用回调函数?
【发布时间】:2019-07-02 15:20:28
【问题描述】:

我需要什么?

当事件发生时,我需要从一个类中调用一个函数来关闭另一个类的UIView。我有一个 UIViewController 和一个 UITableView 和另一个类来管理该 TableView 的单元格。

我的问题是当我尝试在 cellForRowAt: Cannot assign value of type '()' to type '(() -> ())?' 中引用回调函数时。我想在viewDidDisappear 方法上调用这个回调。

代码

class ViewControllerRelatorios : UIViewController, UITableViewDataSource, UITableViewDelegate {

    var closeCellPopup : (()->())? // Ref

    @IBOutlet weak var tableViewContent: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableViewContent.dataSource       = self
        self.tableViewContent.delegate         = self
    }

    override func viewDidDisappear(_ animated: Bool) {
        if closeCellPopup != nil {
            closeCellPopup!() // Here OK
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell2 = tableView.dequeueReusableCell(withIdentifier: "cellDailyReport") as! CellDailyReport
       self.closeCellPopup = cell2.closePopup // Error: Cannot assign value of type '()' to type '(() -> ())?'
       return cell2
    }
}

class CellDailyReport : UITableViewCell {

    var lastView = UIView()

    var closePopup : () {
        self.lastView.removeFromSuperview()
    }
}

如果我将声明 var closeCellPopup : (()->())? 更改为 var closeCellPopup : ()?,我将无法调用此函数。

   override func viewDidDisappear(_ animated: Bool) {
        if closeCellPopup != nil {
            closeCellPopup!() // Cannot call value of non-function type '()'
        }
    }

【问题讨论】:

  • 顺便说一句,if closeCellPopup != nil { closeCellPopup!() } 没用。只要使用closeCellPopup?(),如果是nil,就不会调用闭包,代码会继续运行
  • 您的单元格子类中的closePopup 应该是什么?不是函数类型
  • 所以,我错了,但我必须关闭我的代码中引用的UIView。我是怎么做到的?

标签: ios swift callback closures


【解决方案1】:

有一种更好的方法可以做到这一点,但您可以通过将其设为函数来修复错误。

class CellDailyReport : UITableViewCell {

    var lastView = UIView()

    func closePopup() {
        self.lastView.removeFromSuperview()
    }
}

【讨论】:

    【解决方案2】:

    即使您的闭包变量具有正确的类型,您的代码仍然会设置最后一个出列单元格的引用。

    如果我理解正确,您需要在视图控制器确实消失后从其父视图中删除每个 lastView,这样您就可以遍历表视图的向下转换的单元格

    override func viewDidDisappear(_ animated: Bool) {
        let cells = tableViewContent.visibleCells as! [CellDailyReport]
        cells.forEach { $0.lastView.removeFromSuperView() }
    }
    

    【讨论】:

    • 很好的解决方案,但@Callam 的回答在我的情况下解决了我的问题。
    猜你喜欢
    • 2015-02-16
    • 1970-01-01
    • 2017-09-08
    • 2012-06-27
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多