ios - 快速调用 accessoryButtonTappedForRowWithIndexPath 的格式是什么

标签 ios swift tableview

在我的 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/

相关文章:

ios - 如何在没有登录的情况下在 ios 中显示 facebook 新闻提要?

swift - 如何对私有(private) Cocoapods 库进行单元测试?

swift - 来自 String 的 FontAwesomeSwiftKit 枚举

Swift UI - 如何制作图像网格?

Swing 中的 Javafx 表

Swift - 如何在没有segue的情况下在tableview中选择多行

ios - 在 tableViewCell 上运行动画会阻止用户交互吗?

ios - 在多个 UILabels 上快速使用我的滑动手势功能

ios - 字符串中的内联按钮和/或文本字段,使用 Swift 包装与文本相同的文本

iOS 7.1 默认色调颜色不会为 UISwitch 更改