Keshu Rai Keshu Rai -3 years ago 130
iOS Question

Loading 4 different arrays in table view cells based on the segment control in swift

I am creating a search screen where you can select among four different options. If one selects people, then people array gets loaded in table view cells , if he selects images then image posts get loaded in tableview .

screenshot of the app

how can i achieve the design posted above? i have created four different cells and nib files and based on the option selected in segment control , i have to load those nib files in table cell.

Answer Source

Pretty simple Make a table array i.e common data source for tableView and create 4 array in which actual data is there. Now on each segment tap call like

On Tap of 1st Segment

tableArray = segment_1_Array

On Tap of 2nd Segment

tableArray = segment_2_Array

and so on..

In cellForRow Delegate Method there will be switch statement

let modelObj = tableArray[indexpath.row]
let cellID = ""

switch modelObj {
case _ as CellModelType1 : cellID = "CellType1Identifier"
case _ as CellModelType2 : cellID = "CellType2Identifier"
case _ as CellModelType3 : cellID = "CellType3Identifier"
case _ as CellModelType4 : cellID = "CellType4Identifier"


let cell = tableView.dequeueReusableCell(withIdentifier: cellID) as! TableCell
return cell


1. TableCell will be the SuperClass and all 4 cells will be child class if this class

2. CellModelType1, CellModelType2, CellModelType3, CellModelType4

are different cell Models for example it can be

PeopleCellModel , PostsCellModel, ImagesCellModel and VideoCellModel

Hence you don't have to manage number of rows

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {    
    return tableArray.count
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download