如何构建具有多种单元格类型的 Table 视图?

How to build a Table View with multiple cell types?

我只想在第一个单元格中显示一个数据。我想在另一个单元格中显示与计数数组一样多的数据。我怎样才能做到这一点?我知道少许英文。对不起。我能够将数组名称值打印到屏幕上,但不能打印计数数组。

class ViewController: UIViewController {
    
    var name = ["Sakarya"]
    var count = ["1","2","3","4","5","6","7","8","9"]

    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
}

extension ViewController : UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return name.count
        } else if section == 1 {
            return count.count
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            if let cell = tableView.dequeueReusableCell(withIdentifier: "firstCell") as? FirstTableViewCell {
                cell.prepareForNameLabel(item: name[indexPath.row])
                return cell
            }
        } else if indexPath.section == 1 {
            if let cell2 = tableView.dequeueReusableCell(withIdentifier: "secondaryCell") as? SecondaryTableViewCell {
                cell2.prepareForCount(item: count[indexPath.row])
                return cell2
            }
        }
        return UITableViewCell()
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 75
        } else if indexPath.section == 1 {
            return 60
        }
        return 100
    }
}

由于您在 2 个部分中显示数据,请使用以下委托方法将部分数设置为 2;

func numberOfSections(in tableView: UITableView) -> Int {
    return 2
}