这个问题在这里已有答案:
我想在启用UISwitch
时添加/显示tableview单元格。默认情况下,此UISwitch处于关闭状态。
首先,我在UISwitch
类中定义了这个UITableViewCell
,因为开关位于另一个单元格中。
@IBOutlet weak var listSwitch: UISwitch!
然后 :
在控制器中:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let FirsteCell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! NewlistViewCell
return FirsteCell
} else if indexPath.row == 1 {
let secondCell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as! NewlistViewCell
let switchCase = NewlistViewCell()
if switchCase.listSwitch.isOn {
return secondCell
} else {
return UITableViewCell()
}
}
return UITableViewCell()
}
但我得到了这个错误:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
我可以指导一下问题的来源吗?非常感谢
不要创建另一个NEWlistViewCell类型的对象。你只需要使用你已经制作过的细胞。通过使用以下代码,您可以删除此错误。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let FirsteCell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! NewlistViewCell
return FirsteCell
} else if indexPath.row == 1 {
let secondCell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as! NewlistViewCell
if secondCell.listSwitch.isOn {
return secondCell
} else {
return UITableViewCell()
}
}
return UITableViewCell()
}