Skip to content

Instantly share code, notes, and snippets.

@licvido
Created March 9, 2015 20:57
Show Gist options
  • Save licvido/a78f3714a7eda01b3c62 to your computer and use it in GitHub Desktop.
Save licvido/a78f3714a7eda01b3c62 to your computer and use it in GitHub Desktop.
SWIFT: UITableView sections example
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: UITableView!
var itemsInSections: Array<Array<String>> = [["1A", "1B", "1C"], ["2A", "2B"], ["3A", "3B", "3C", "3D", "3E"]]
var sections: Array<String> = ["Section 1", "Section 2", "Section 3"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = self
self.tableView.delegate = self
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.sections.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.itemsInSections[section].count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sections[section]
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
var text = self.itemsInSections[indexPath.section][indexPath.row]
cell.textLabel!.text = text
return cell
}
}
@kanic61
Copy link

kanic61 commented Feb 20, 2018

Thanks for taking time to post this example! I was having trouble digesting how the "table" process was finding my section titles. Now I understand. Great that your example also illustrates that the number of items per section can vary.

@mstysin
Copy link

mstysin commented Jun 20, 2018

Worked for me only when I added underscore in cellForRow:
override func tableView(_ tableView:

@alifareed
Copy link

Thanks!

Copy link

ghost commented Nov 17, 2019

Thanks!

@caroline-zaini
Copy link

thanks ! I wonder how do you pass the selected item to an another ViewController in this case ?

@wesleydst404
Copy link

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment