下面的代码有效,但可能有更好的方法。我的目标是在退出编辑模式时从 UITableCell 调用 UIViewController 函数。
我通过为每个 UITableViewCell 设置实例化的 UIViewController 引用,然后在 UITableViewCell 状态更改时调用函数 CancelDelete() 来实现这一点。
代码似乎效率低下,因为对于每个 MyCell,我首先将占位符 MyViewContoller 实例化为公共(public)变量,然后在 UITableView 初始化时将其替换为对 UIViewController 的引用。
有更好的方法吗?
class MyCell : UITableViewCell
{
var previousState : UITableViewCellStateMask = UITableViewCellStateMask.allZeros
// This holds a reference to the parent view controller
// Seems wasteful to instantiate since it gets replaced
var controller:MyViewController = MyViewController()
// This is called when the user aborts edit mode
override func willTransitionToState(state: UITableViewCellStateMask) {
if state & UITableViewCellStateMask.ShowingEditControlMask != nil {
if previousState & UITableViewCellStateMask.ShowingDeleteConfirmationMask != nil {
// send notification to controller
controller.CancelDelete(self)
}
}
previousState = state
}
}
class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Give cell access to this controller
var cell:MyCell = tableView.dequeueReusableCellWithIdentifier("cell") as MyCell
cell.controller = self
cell.tag = indexPath.row
}
// This is called from the table cell
func CancelDelete(cell:MyCell) {
editButtons[cell.tag].hidden = false
}
}
最佳答案
将 controller
的类型更改为 MyViewController!
而不是 MyViewController
。此外,将其设置为默认值 nil
。
controller
的声明应该是这样的:
var controller: MyViewController! = nil
如果您对以感叹号 (!
) 结尾的类型有任何疑问,请查看:
https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html
(在名为Optionals 的部分)。
关于uitableview - UITableViewCell 和 UIViewController 之间通信的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28129559/