ReversedcigoL ReversedcigoL - 14 days ago 8
iOS Question

How to perform a dynamic creation of sections and cells to a UITableView in SWIFT 3

I've got a sample code but rows per section won't show, since numberOfRowsInSection doesn't exist in SWIFT 3 anymore.

I currently have the ff code:

let section = ["pizza", "deep dish pizza", "calzone"]

let items = [["Margarita", "BBQ Chicken", "Pepperoni"], ["sausage", "meat lovers", "veggie lovers"], ["sausage", "chicken pesto", "prawns", "mushrooms"]]

override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {

return self.section[section]

}

override func numberOfSections(in tableView: UITableView) -> Int {
return self.section.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)

// Configure the cell...

cell.textLabel?.text = self.items[indexPath.section][indexPath.row]

return cell
}


Result:

enter image description here

Can someone show the correct code for updated swift 3? Thanks!

Answer

For your information numberOfRowsInsection exists in swift3, see below

 override func numberOfSections(in tableView: UITableView) -> Int {
    return section.count
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return items[section].count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
    cell?.textLabel?.text = items[indexPath.section][indexPath.row]
    return cell!
}

Thanks:)

Comments