首页 > 解决方案 > TableViewController 中的多个自定义单元格

问题描述

设想


| 第一单元 |



| 第二单元 | | 开关 | | |



| 第三单元 | | 文本字段 |


我创建了一个具有三个不同类的动态表视图:(SecondTableCell里面有一个开关的出口)和ThirdTableCell(里面有一个 textField 的出口)

开关关闭。

我需要看看textField.isUserInteractionEnabled = false开关是否打开。

我怎样才能做到这一点?

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var customTableView: UITableView!

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cellSwitch = tableView.dequeueReusableCell(withIdentifier: "cellSwitch")! as! SwitchTableViewCell
        let cellText = tableView.dequeueReusableCell(withIdentifier: "cellText")! as! TextFieldTableViewCell

}

class SwitchTableViewCell: UITableViewCell {

    @IBOutlet weak var switchOutlet: UISwitch!

    @IBAction func switchAction(_ sender: UISwitch) {
        if sender.isOn == true{
            print("swithOn")
        }else{
            print("swithOff")
        }
    }

}


class TextFieldTableViewCell: UITableViewCell {

    @IBOutlet weak var textFieldColor: UITextField!
}

标签: swiftuitableview

解决方案


class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, SwitchDelegate {

    @IBOutlet weak var customTableView: UITableView!

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


        let cellSwitch = tableView.dequeueReusableCell(withIdentifier: "cellSwitch")! as! SwitchTableViewCell
        let cellText = tableView.dequeueReusableCell(withIdentifier: "cellText")! as! TextFieldTableViewCell

        cellSwitch.delegate = self
        cellText.delegate = self
    }

    func valueDidChange(isOn: Bool) {
        tableView.visibleCells.forEach { cell
            if let cell = cell as? TextFieldTableViewCell {
                cell.textField.isUserInteractionEnabled = false
            }
        }
    }

}

protocol SwitchDelegate {
    func valueDidChange(isOn: Bool)
}

class SwitchTableViewCell: UITableViewCell {

    @IBOutlet weak var switchOutlet: UISwitch!
    var delegate: SwitchDelegate?

    @IBAction func switchAction(_ sender: UISwitch) {
        delegate?.valueDidChange(isOn: sender.isOn)
    }
} 


class TextFieldTableViewCell: UITableViewCell {
     @IBOutlet weak var textField: UITextField!
}

推荐阅读