【问题标题】:getting the index path of a cell inside UITableViewCell in swift快速获取 UITableViewCell 中单元格的索引路径
【发布时间】:2015-09-21 19:56:03
【问题描述】:

谁能告诉我如何在 UISwitch 的动作函数中获取其类中的单元格的索引,更具体地说,它是 uitableViewCell。 我做了以下..

        var cell = sender.superview?.superview as UITableViewCell
        var table: UITableView = cell.superview as UITableView
        let indexPath = table.indexPathForCell(cell)

但随后它崩溃了。 解决办法是什么?

【问题讨论】:

  • 它在哪一行崩溃?错误说明了什么?
  • 它说:“Swift 动态转换失败”。如果我只写第一行投射到 uitableVewCell,它就会崩溃。即使我写 { var cell = sender.superview as UITableViewCell } 它也会崩溃
  • 你不应该这样做,一个单元格不应该知道它在 tableView 中的索引是什么。但是,如果以某种方式可行,您可能希望将“self”从单元格传递到 tableView 方法中。
  • func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 中配置单元格时,配置一个闭包作为调用开关时的操作。 Read this
  • @JMFR 然后,如何从自定义单元格类中调用此闭包?

标签: xcode swift xcode6


【解决方案1】:

试试这个:

假设您在 cell 自定义类中有一个 UISwitch *cellSwitch 对象

cellForRowAtIndexPath:

cell.cellSwitch.tag = indexPath.row

IBAction 中用于此开关:

let indexPath = NSIndexPath(forRow: sender.tag, inSection: 0)

【讨论】:

  • cellForRowAtIndexPath 不是 UITableView 函数吗?如何在不引用 tableView 的情况下使用它?我没明白你的意思。
  • 如果你在这里添加你的 cellForRowAtIndexPath 方法,我可以解释一下
  • 如果您有自定义单元格,请确保始终转换为自定义单元格类而不是 UITableViewCell。 @Nishant 解决方案是最好的方法。干净的方法。
  • @Nishant 可以详细写代码吗?我还没有理解你。 ://
  • @يعربالمصطفى:正如我所说,如果你在这里添加你的 cellForRowAtIndexPath 方法,我可以详细解释
【解决方案2】:

您不想知道单元格内部的单元格的索引路径。索引路径是 UITableViewController 的一个实现细节。单元格应该是一个独立的对象。

您真正想要做的是分配一个动作以在您的开关更改时运行。

class MySwitchCell: UITableViewCell {

    @IBOutlet weak var switchCellLabel: UILabel!
    @IBOutlet weak var mySwitch: UISwitch!

    //Declare an action to be run
    var action: ((sender: UISwitch) -> Void)?
    //then run it
    @IBAction func switchAction(sender: UISwitch) {
        action?(sender: sender)
    }

}

然后在您配置单元格时让操作执行一些操作。

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("SwitchCell", forIndexPath: indexPath) as! MySwitchCell

        cell.switchCellLabel.text = items[indexPath.row]
        cell.mySwitch.on = NSUserDefaults.standardUserDefaults().boolForKey(items[indexPath.row])
        cell.action = { [weak self] sender in
            if let tableViewController = self {
                NSUserDefaults.standardUserDefaults().setBool(sender.on, forKey: tableViewController.items[indexPath.row]) }
        }
        return cell
    }

例如,这个基于该开关的状态在 NSUserDefaults 中设置一个布尔值。

您可以从https://github.com/regnerjr/SimpleCellSwitchAction签出整个示例项目

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 2018-08-10
    相关资源
    最近更新 更多