UITableViewCell和UIViewController之间通信的最佳方式
下面的代码可以工作,但可能有更好的方法。我的目标是在从编辑模式中止时从UITableCell调用UIViewController函数 为此,我将实例化的UIViewController引用设置为每个UITableViewCell,然后在UITableViewCell状态更改时调用函数CancelDelete() 代码似乎效率低下,因为对于每个MyCell,我首先实例化占位符MyViewContoller作为公共变量,然后在UITableView初始化时将其替换为对UIViewController的引用 有更好的方法吗UITableViewCell和UIViewController之间通信的最佳方式,uitableview,swift,uiviewcontroller,Uitableview,Swift,Uiviewcontroller,下面的代码可以工作,但可能有更好的方法。我的目标是在从编辑模式中止时从UITableCell调用UIViewController函数 为此,我将实例化的UIViewController引用设置为每个UITableViewCell,然后在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
}
}
将
控制器的类型更改为MyViewController代码>而不是MyViewController
。另外,将其设置为默认值nil
控制器的声明应如下所示:
var controller: MyViewController! = nil
如果您对以感叹号(!
)结尾的类型有任何疑问,请查看:
(在名为Optionals的部分中)。有效。是的,我显然还需要训练。这是正确的沟通技巧吗?我曾希望我可以在不必显式设置的情况下确定UITableViewCell的拥有者ViewController。我不知道是否有正确的方法,但这在不需要占位符的情况下有效。