xcode 快速获取 UITableViewCell 中单元格的索引路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32703486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getting the index path of a cell inside UITableViewCell in swift
提问by ???? ???????
could anyone tell me how to get the index of a cell inside its class which is uitableViewCell more specifically , inside an action function of UISwitch . I did the following..
谁能告诉我如何在 UISwitch 的动作函数中获取其类中单元格的索引,更具体地说,是 uitableViewCell 。我做了以下..
var cell = sender.superview?.superview as UITableViewCell
var table: UITableView = cell.superview as UITableView
let indexPath = table.indexPathForCell(cell)
but then it crashes. what is the solution ?
但随后它崩溃了。解决办法是什么 ?
回答by Nishant
Try this:
尝试这个:
Assuming you have a UISwitch *cellSwitch
object in cell
custom class
假设您UISwitch *cellSwitch
在cell
自定义类中有一个对象
In cellForRowAtIndexPath
:
在cellForRowAtIndexPath
:
cell.cellSwitch.tag = indexPath.row
In IBAction
for this switch:
在IBAction
此开关中:
let indexPath = NSIndexPath(forRow: sender.tag, inSection: 0)
回答by JMFR
You don't want to know the index path of the cell inside of the cell. The index path is an implementation detail of the UITableViewController. The cell should be an independent object.
您不想知道单元格内部单元格的索引路径。索引路径是 UITableViewController 的一个实现细节。单元格应该是一个独立的对象。
What you really want to do is to assign an action to run when your switch is changed.
您真正想要做的是分配一个动作以在您的开关更改时运行。
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)
}
}
Then give the action something to do when you configure the cell.
然后在配置单元时指定要执行的操作。
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
}
For example this one sets a bool in the NSUserDefaults based on the state of that switch.
例如,这个基于该开关的状态在 NSUserDefaults 中设置一个布尔值。
You can checkout the whole sample project from https://github.com/regnerjr/SimpleCellSwitchAction
您可以从https://github.com/regnerjr/SimpleCellSwitchAction查看整个示例项目