Created
March 9, 2015 20:57
-
-
Save licvido/a78f3714a7eda01b3c62 to your computer and use it in GitHub Desktop.
SWIFT: UITableView sections example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Worked for me only when I added underscore in cellForRow:
override func tableView(_ tableView:
Thanks!
Thanks!
thanks ! I wonder how do you pass the selected item to an another ViewController in this case ?
thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.