在我的 iOS表格视图中我有TableViewDelegate
所需的功能:
override func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) {
savedRow = indexPath.row
self.performSegueWithIdentifier("SubcategorySegue", sender: self)
}
首先通过执行以下操作获取indexPath
:
@IBAction func showSubcategoryEditor(sender: UIButton) {
let switchFrameOrigin = sender.frame.origin
if let indexPath: NSIndexPath = self.tableView.indexPathForRowAtPoint(switchFrameOrigin) {
tableView.delegate.accessoryButtonTappedForRowWithIndexPath!(indexPath)
}
}
这会导致错误,表明无法识别代理。
我应该使用:tableView.accessoryButtonTappedForRowWithIndexPath(indexPath)
吗?
答案 0 :(得分:4)
当您使用系统提供的附件按钮,并点击按钮时,系统会为您调用accessoryButtonTappedForRowWithIndexPath,并且系统会传入正确的indexPath。当您自己调用该方法时,您必须传入indexPath,它是从indexPathForRowAtPoint传入的(但您需要将该点转换为表视图的坐标系,就像我在下面的代码中所示)。因此,由于你已经在按钮的action方法中有了indexPath,所以不需要调用accessoryButtonTappedForRowWithIndexPath,这只是一个额外的步骤,它不会比你在按钮的action方法中做的更多。你只需要这样做,
@IBAction func showSubcategoryEditor(sender: UIButton) {
let hitPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
if let indexPath: NSIndexPath = self.tableView.indexPathForRowAtPoint(hitPoint) {
savedRow = indexPath.row
self.performSegueWithIdentifier("SubcategorySegue", sender: indexPath)
}
}
另请注意,在performSegue:sender:中,我将indexPath作为sender参数传递。然后,您可以在prepareForSegue:sender:中使用它来获取行,如果您需要将信息传递给目标视图控制器。
如果将segue从按钮连接到下一个控制器,那么甚至不需要按钮操作方法;一切都可以在prepareForSegue:sender:中完成。 sender参数将是按钮,所以你可以这样做,
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let button = sender as UIButton
let controller = segue.destinationViewController as DetailViewController // substitute the class of your destination view controller
let hitPoint = button.convertPoint(CGPointZero, toView: self.tableView)
if let indexPath: NSIndexPath = self.tableView.indexPathForRowAtPoint(hitPoint) {
// pass the index path to controller, or get data from your array based on the indexPath, and send that to controller
}
}
答案 1 :(得分:0)
答案是在Apple论坛上提供的:
在
UITableViewController
子类中,实现了 委托协议,您可以像这样调用委托方法:
tableView(tableView, accessoryButtonTappedForRowWithIndexPath:
indexPath)