使用UISwitch隐藏/显示tableview单元格[复制]

问题描述 投票:-1回答:1

我想在启用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

我可以指导一下问题的来源吗?非常感谢

swift uitableview uiswitch
1个回答
0
投票

不要创建另一个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()
}
© www.soinside.com 2019 - 2024. All rights reserved.