【发布时间】: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