Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill tableview with two arrays using single custom cell?

I want to display two array values in tableview using single cell. Suppose i have two array and both contains same no of elements.

FirstArray and SecondArray. there is two label in tableview cell Lbl1 and Lbl2, now Lbl1 should fill with FirstArray and Lbl2 Should fill with SecondArray. I know that we can not use two array for uitableview datasource . I can not figure out how to do this.

Please help me.

I also tried using multiple custom tableview cells with section. but it did not give the desired result.

I have two Array -

let datalist1 = ["firstCell1" , "firstCell2" , "firstCell3" , "firstCell4"]
    let datalist2 = ["secondCell1"  ,"secondCell2" , "secondCell3" ,"secondCell4"]

In tableview numberOfRowsInSection :

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

        if section == 0
        {
            return datalist1.count
        }
        else  {
            return datalist2.count
        }
    }

In cellForRowAt :

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

        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as? FirstCell
            cell?.initData(name: datalist1[indexPath.row])
            return cell!
        }
        else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as? SecondCell
            cell?.initData(lbl: datalist2[indexPath.row])
            return cell!
        }

    }

Actual Output :

FirstCell1 FirstCell2 FirstCell3 FirstCell4 SecondCell1 SecondCell2 SecondCell3 SecondCell4

Expected Output:

FirstCell1 SecondCell1 FirstCell2 SecondCell2 FirstCell3 SecondCell3 FirstCell4 SecondCell4

like image 771
PUJA SINGH Avatar asked Nov 25 '25 21:11

PUJA SINGH


1 Answers

Hello You not need to add two section just do as bellow. This is your arrays.

let datalist1 = ["firstCell1" , "firstCell2" , "firstCell3" , "firstCell4"]
let datalist2 = ["secondCell1"  ,"secondCell2" , "secondCell3" ,"secondCell4"]

Number of rows

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


    return datalist1.coun
}

Cell for row

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as? FirstCell
    cell.Lbl1.text = datalist1[indexPath.row]
    cell.Lbl2.text = datalist2[indexPath.row]
    return cell!
}
like image 123
Harsh Pipaliya Avatar answered Nov 27 '25 13:11

Harsh Pipaliya