Ufuk Köşker
Ufuk Köşker

Reputation: 1470

How to build a Table View with multiple cell types?

I want to show only 1 data in the first cell. I want to show as much data as the count array in the other cell. How can I do that? I know little English. I'm sorry. I was able to print the array name values ​​to the screen, but not the count array.

enter image description here

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
    }
}

Upvotes: 1

Views: 1247

Answers (1)

Jithin
Jithin

Reputation: 943

Since you are displaying data in 2 sections, set number of sections as 2 with the following delegate method;

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

Upvotes: 2

Related Questions