在 swift 中获取 UITableViewCell 中单元格的索引路径

getting the index path of a cell inside UITableViewCell in swift

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

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

但随后它崩溃了。 解决方案是什么?

试试这个:

假设您在 cell 自定义 class

中有一个 UISwitch *cellSwitch 对象

cellForRowAtIndexPath中:

cell.cellSwitch.tag = indexPath.row

IBAction 中,此开关:

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

你不想知道单元格内部单元格的索引路径。索引路径是 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

查看整个示例项目