在我的 iOS 表格 View 中,我有一个 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)
}
}
这会导致错误,指示无法识别委托(delegate)。
我应该使用:tableView.accessoryButtonTappedForRowWithIndexPath(indexPath)
吗?
最佳答案
当您使用系统提供的辅助按钮并点击该按钮时,系统会为您调用 accessoryButtonTappedForRowWithIndexPath,并传入正确的 indexPath。当您自己调用该方法时,您必须传入从 indexPathForRowAtPoint 获取的 indexPath(但您需要将该点转换为 TableView 的坐标系,如我在下面的代码中所示)。因此,由于您在按钮的操作方法中已经有了 indexPath,因此无需调用 accessoryButtonTappedForRowWithIndexPath,这只是一个额外的步骤,不会比您在按钮的操作方法中做的更多。你只需要这样做,
@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 参数传递。然后,如果您需要将信息传递到目标 View Controller ,则可以在 prepareForSegue:sender: 中使用它来获取行。
如果您将 segue 从您的按钮连接到下一个 Controller ,那么甚至不需要按钮操作方法;一切都可以在 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
}
}
关于ios - 快速调用 accessoryButtonTappedForRowWithIndexPath 的格式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28254818/