Swift UITableView
Delegate
We should implement UITableViewDelegate, UITableViewDataSource to manage UITableView
Methods
We need to implement UITableViewDelegate, UITableViewDataSource methods
| Method | Delegate | Description |
|---|---|---|
| tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int | Number of table row | |
| tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) | Handle cell select event | |
| tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? | Return header title | |
| tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell | Create table view cell of each row and section |
Sample
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
private let kCELLIDENTIFIER = "Cell"
private var tableView : UITableView?
override func viewDidLoad() {
super.viewDidLoad()
self.tableView = UITableView()
self.tableView?.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
self.tableView?.delegate = self
self.tableView?.dataSource = self
self.view .addSubview(self.tableView!)
self.tableView?.registerClass(UITableViewCell.self, forCellReuseIdentifier: kCELLIDENTIFIER)
self.tableView?.reloadData()
}
// MARK: UITableView
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier(kCELLIDENTIFIER, forIndexPath: indexPath) as UITableViewCell
cell.textLabel.text = "Table Title"
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
// Select Event
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Header title"
}
}
