Xcode 在swift中获取UITableViewCell内单元格的索引路径
有谁能告诉我,如何在UISwitch的action函数中获取其类(更具体地说是uitableViewCell)中单元格的索引。 我做了以下几件事Xcode 在swift中获取UITableViewCell内单元格的索引路径,xcode,swift,xcode6,Xcode,Swift,Xcode6,有谁能告诉我,如何在UISwitch的action函数中获取其类(更具体地说是uitableViewCell)中单元格的索引。 我做了以下几件事 var cell = sender.superview?.superview as UITableViewCell var table: UITableView = cell.superview as UITableView let indexPath = table.indexPathForCell(c
var cell = sender.superview?.superview as UITableViewCell
var table: UITableView = cell.superview as UITableView
let indexPath = table.indexPathForCell(cell)
但后来它崩溃了。
解决方案是什么?试试这个:
假设您在cell
自定义类中有一个UISwitch*cellSwitch
对象
在单元格中,按行索引路径
:
cell.cellSwitch.tag = indexPath.row
在此开关的iAction
中:
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中设置布尔值
您可以从哪一行检查整个示例项目?错误说明了什么?它说:“Swift dynamic cast失败”。如果我只写第一行,它将转换为uitableVewCell,它将崩溃。即使我将{var cell=sender.superview写为UITableViewCell}它也会崩溃您不应该这样做,一个单元格不应该知道它在tableView中是什么索引。但是,如果这能起作用,您可能希望将的“self”从单元格传递到tableView方法中。在
func tableView(\uTableView:UITableView,cellForRowAtIndexPath indexPath:NSIndexPath)->UITableViewCell
中配置一个闭包,以便在调用开关时用作操作@那么,我如何从自定义单元格类调用这个闭包呢?CellForRowatineXpath不是UITableView函数吗?如何在不引用tableView的情况下使用它?我不明白你的意思。如果你在这里添加cellForRowAtIndexPath方法,我可以解释一下。如果你有自定义单元格,请确保你总是强制转换到自定义单元格类而不是UITableViewCell@尼桑溶液是最好的方法。干净的方法。@Nishant可以详细地写代码吗?我还没听懂你的意思/@如我所说,如果您在此处添加cellForRowAtIndexPath
方法,我可以详细解释