3rdeye7
3rdeye7

Reputation: 536

iOS Custom UItableviewcell sections

Just trying to understand how and if its possible to make custom UItableview with 3 sections of custom cells, similar to below.

           Sensor Info
====================== 
Sensor 1: $Value_1   
Sensor 2: $Value_2
Sensor 3: $Value_3
Sensor 4: $Value_4   
Sensor 5: $Value_5
Sensor 6: $Value_6

             Errors
===================
Error 1  :  $error1
Error 2..:  $error2..

       Another Section
========================
Error 1  :  $error1
Error 2..:  $error2..

One suggestion might be to add all the content into one array and then populate the table but i need each segment to load after another. Each segments content are generated from methods within the view controller class after a button is pressed. So Sensor Info, Errors, another section and more if i do plan to add later on.

Im having a hard time trying to grasp how to build a table with different row syles for each section. I would like to make all sensor data custom cell and the subtitle cells or right detail.

Upvotes: 0

Views: 131

Answers (1)

GIJOW
GIJOW

Reputation: 2343

You can have as many sources and sections you want your table.

You can even have a prototyped cell for each section.

Just verify where you are and handle it like:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 44
}

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

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if (section == 0) {
        return "Title 1"
    }
    if (section == 1) {
        return "Title 2"
    }          
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
        return contactPhones.count
    } else if section == 1 {
        return contactEmails.count
    } else {
        return 1
    }
}

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cellIdentifier: String = "Cell"
    var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as UITableViewCell!
    if cell == nil {
        cell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: cellIdentifier)
    }

    if indexPath.section == 0 {
        cell?.textLabel?.text = contactPhones[indexPath.row]["phoneNumber"].stringValue
        cell?.imageView?.image = UIImage(flagImageWithCountryCode: contactPhones[indexPath.row]["phoneCountryCode"].stringValue)
    } else if indexPath.section == 1 { 
        cell?.textLabel?.text = contactEmails[indexPath.row]["emailAddress"].stringValue
    }

    return cell!
}

Upvotes: 1

Related Questions