如何为swift中的每个单元格添加不同的附件(或子视图)?

How to add different accessories(or subviews) for each cell in swift?

我使用 UITableViewCell subclass 'FruitTableViewCell' class.

制作了 4 个相同的带有子视图的单元格

FruitTableViewCell.swift

class FruitTableViewCell: UITableViewCell, UITextFieldDelegate {
    var fruitsTextField = UITextField()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.contentView.addSubview(fruitsTextField)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        fruitsTextField.frame = CGRect(x: 100, y: 7.5, width: 50, height: 30)
        fruitsTextField.backgroundColor = UIColor.darkGray
        fruitsTextField.delegate = self

    }
}

TableViewController.swift

class TableViewController: UITableViewController, UITextFieldDelegate {
    let fruitsComponents: [String] = ["Apple", "Banana", "Grape", "Pear"]
    let cellReuseidentifier = "cell"

    override func viewDidLoad() {
    super.viewDidLoad()

    tableView.register(FruitTableViewCell.self, forCellReuseIdentifier: cellReuseidentifier)

    }

    override func numberOfSections(in tableView: UITableView) -> Int {
    sections

    return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return fruitsComponents.count
    }


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

        let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseidentifier, for: indexPath) as! FruitTableViewCell
        cell.textLabel?.text = fruitsComponents[indexPath.row]
        return cell

    }
}

效果很好。

但实际上,我想为每个单元格添加不同的附件(或子视图)。 UITextField 的第 0 行,UILabel 的第 1 行,Stepper 的第 2 行,UILabel 的第 3 行,...等等。

所以我制作了另一个UITableViewCell子class 'AnotherFruitTableViewCell' class来使用

我尝试使用 'if' 语句。

已修订 TableViewController.swift

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.row == 0 {

        let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseidentifier, for: indexPath) as! FruitTableViewCell
        cell.textLabel?.text = fruitsComponents[indexPath.row]
        return cell
    } else {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseidentifier, for: indexPath) as! AnotherFruitTableViewCell
        cell.textLabel?.text = fruitsComponents[indexPath.row]
        return cell
    }

但是消息 'could not cast value of type' 弹出。 因为这段代码,我觉得。

override func viewDidLoad() {

    super.viewDidLoad()

    tableView.register(FruitTableViewCell.self, forCellReuseIdentifier: cellReuseidentifier)

}

而且从根本上说,我认为 'if' 语句不是为每个单元格添加不同附件的好方法。

如何为每个单元格添加不同的附件(或子视图)?

您注册了您的 FruitTableViewCell 但未注册 AnotherFruitTableViewCell