【问题标题】:How to Translate a Delegated Function to a IBAction Function如何将委托函数转换为 IBAction 函数
【发布时间】:2015-09-21 16:30:25
【问题描述】:

我有一个委托函数,可以在点击时更改 UITableViewCell 的部分位置:

//On cell tap, expand
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if indexPath.section == 0
    {
        let data = firstDataSource[indexPath.row]

        tableView.beginUpdates()
        secondDataSource.append(data)
        firstDataSource.removeAtIndex(indexPath.row)

        let newIndexPath = NSIndexPath(forRow: find(secondDataSource, data)!, inSection: 1)

        tableView.moveRowAtIndexPath(indexPath, toIndexPath: newIndexPath)
        tableView.endUpdates()
    } else if indexPath.section == 1 {
        let data = secondDataSource[indexPath.row]

        tableView.beginUpdates()
        firstDataSource.append(data)
        secondDataSource.removeAtIndex(indexPath.row)

        let newIndexPath = NSIndexPath(forRow: find(firstDataSource, data)!, inSection: 0)

        tableView.moveRowAtIndexPath(indexPath, toIndexPath: newIndexPath)
        tableView.endUpdates()
    }
}

我希望通过点击按钮触发 IBAction 时执行此操作,但我不确定如何访问委托函数中给出的 indexPath 参数。这是我当前的 IBAction 按钮代码:

@IBAction func checkOffTask(sender: UIButton) {
    var checkedOff = false


    let indexOfCell = sender.tag
    sender.setImage(UIImage(named: "checkbox-checked"), forState: UIControlState.Normal)
    self.tableView.beginUpdates()
    self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forItem: indexOfCell, inSection: 1)], withRowAnimation: UITableViewRowAnimation.Automatic)
    self.tableView.endUpdates()

}

知道如何让委托函数为 IBAction 函数工作吗?

【问题讨论】:

  • 行动来自谁? IBAction 只是目标/动作模式的图形连接版本,通常源自 iOS 中的 UIControl 子类。
  • 动作来自 UIButton 视图。
  • 那么您希望它与哪一行相关联?当前选择的一个?
  • 是的,每一行都有自己的按钮,所以每当点击该按钮时,该特定行应该更改部分位置。
  • 你的问题不是已经用NSIndexPath(forItem: indexOfCell, inSection: 1)解决了吗?

标签: ios swift uitableview cocoa-touch uikit


【解决方案1】:

好的,所以您的操作来自一个按钮,该按钮位于表格视图单元格内,问题是:该表格视图单元格的 indexPath 是什么。

最简单的方法是:

  1. 获取按钮在表格视图中的位置;
  2. 请求该位置的索引路径。

例如

@IBAction func checkOffTask(sender: UIButton!) {
    let originInTableView = self.tableView.convertPoint(CGPointZero, fromView: sender)
    let indexPath = self.tableView.indexPathForRowAtPoint(originInTableView)
}

【讨论】:

    【解决方案2】:

    好的,这是我以前使用过的解决方法。 看起来不漂亮,但确实可以:

    UIButton *likeButton = (UIButton *)sender;
    UITableViewCell *cell = (UITableViewCell *)likeButton.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    

    只需为 UICollectionView 类类型的按钮找到正确的超级视图。

    附: - 我的 Swift 不是最好的。希望你能转换它。

    【讨论】:

    • 好人,我不知道你可以选择这样的超级视图,这很甜蜜。我能够将它翻译成 Swift 并且运行良好,非常感谢!
    • 这可能会在未来的 iOS 版本中中断。单元格的 contentView 在其父级中没有保证嵌套。如果您的代码不再是直接子代,您的代码将会失败。
    猜你喜欢
    • 1970-01-01
    • 2014-06-09
    • 2014-10-13
    • 1970-01-01
    • 1970-01-01
    • 2011-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多