【发布时间】:2015-01-24 19:51:16
【问题描述】:
下面的代码有效,但可能有更好的方法。我的目标是从编辑模式中止时从 UITableCell 调用 UIViewController 函数。
我这样做是通过为每个 UITableViewCell 设置一个实例化的 UIViewController 引用,然后在 UITableViewCell 状态更改时调用一个函数 CancelDelete()。
代码似乎效率低下,因为对于每个 MyCell,我首先将占位符 MyViewContoller 实例化为公共变量,然后在 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
}
}
【问题讨论】:
标签: uitableview swift uiviewcontroller