Delegate and Datasource
suggest changeThe UITableViewDelegate controls how the table is displayed, and UITableViewDataSource defines the table’s data. Two data-source methods are required. Many other methods are optional and customize size, sections, headings, and cells.
myArray, numSections, labelFrame, and btnFrame in the samples below must already exist. MyCustomCell is a UITableViewCell subclass with a titleLabel.
UITableViewDataSource
Required Methods
tableView:numberOfRowsInSection:defines how many cells each section displays.
Objective-C
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Usually the count of an array, or a fixed number.
return self.myArray.count;
}
Swift 3
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.myArray.count
}
tableView:cellForRowAtIndexPath:creates and configures each cell. Return aUITableViewCellor a subclass. Do not return nil.
Note: dequeueReusableCellWithIdentifier:forIndexPath: requires the class or nib to be registered for that identifier with registerClass:forCellReuseIdentifier: or registerNib:forCellReuseIdentifier:. That is usually done in viewDidLoad. In Swift 3 the names are dequeueReusableCell(withIdentifier:for:) and register(_:forCellReuseIdentifier:).
Objective-C
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCustomCell" forIndexPath:indexPath];
cell.titleLabel.text = [NSString stringWithFormat:@"Title Row %ld", (long)indexPath.row];
return cell;
}
Swift 3
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCustomCell", for: indexPath) as! MyCustomCell
cell.titleLabel.text = "Title Row \(indexPath.row)"
return cell
}
Optional Methods
tableView:titleForHeaderInSection:returns the title for a section header. For a custom header view, implementtableView:viewForHeaderInSection:instead.
Objective-C
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
switch (section) {
case 0:
return @"Title 1";
case 1:
return @"Title 2";
default:
return nil;
}
}
Swift 3
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return "Title 1"
case 1:
return "Title 2"
default:
return nil
}
}
tableView:titleForFooterInSection:returns the title for a section footer.
Objective-C
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
return @"Footer text";
}
Swift 3
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return "Footer text"
}
tableView:canEditRowAtIndexPath:returns whether the editing controls should appear for that row.
Objective-C
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
Swift 3
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
tableView:commitEditingStyle:forRowAtIndexPath:inserts or deletes the row in both the table and the data model. Update the model before inserting or deleting rows, or the table will throw an inconsistency exception.
Objective-C
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
switch (editingStyle) {
case UITableViewCellEditingStyleInsert:
[self insertNewDataIntoDataModel];
[tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
break;
case UITableViewCellEditingStyleDelete:
[self removeDataFromDataModelAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
break;
default:
break;
}
}
Swift 3
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
switch editingStyle {
case .insert:
self.insertNewDataIntoDataModel()
tableView.insertRows(at: [indexPath], with: .automatic)
case .delete:
self.removeDataFromDataModelAtIndex(indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
default:
break
}
}
tableView:editActionsForRowAtIndexPath:adds extra swipe actions, such as Edit next to Delete.
Swift 3
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let editAction = UITableViewRowAction(style: .normal, title: "Edit", handler: { action, indexPath in
// Handle the edit tap. `action` is this row action.
})
editAction.backgroundColor = UIColor.blue
let deleteAction = UITableViewRowAction(style: .destructive, title: "Delete", handler: { action, indexPath in
// Handle the delete tap.
})
return [deleteAction, editAction]
}
UITableViewDelegate
Every UITableViewDelegate method is optional. The methods below add behavior on top of the data source.
numberOfSectionsInTableView:is a data source method, not a delegate method. The default is 1.
Objective-C
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return self.numSections;
}
Swift 3
func numberOfSections(in tableView: UITableView) -> Int {
return self.numSections
}
tableView:viewForHeaderInSection:supplies a custom header view.labelFrameandbtnFrameare rectangles in that header.
Objective-C
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 22)];
view.backgroundColor = [UIColor groupTableViewBackgroundColor];
UILabel *label = [[UILabel alloc] init];
label.font = [UIFont systemFontOfSize:12];
label.textColor = [UIColor darkGrayColor];
switch (section) {
case 1: {
label.text = @"Title";
label.frame = labelFrame;
UIButton *more = [[UIButton alloc] initWithFrame:btnFrame];
[more setTitle:@"See more" forState:UIControlStateNormal];
[more.titleLabel setFont:[UIFont systemFontOfSize:12]];
[view addSubview:more];
break;
}
default:
label.frame = CGRectZero;
break;
}
[view addSubview:label];
return view;
}
Swift 3
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 22))
view.backgroundColor = UIColor.groupTableViewBackground
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 12)
label.textColor = UIColor.darkGray
switch section {
case 1:
label.text = "Title"
label.frame = labelFrame
let more = UIButton(frame: btnFrame)
more.setTitle("See more", for: .normal)
more.titleLabel?.font = UIFont.systemFont(ofSize: 12)
view.addSubview(more)
default:
label.frame = CGRect.zero
}
view.addSubview(label)
return view
}
tableView:heightForRowAtIndexPath:sets the height of each cell.
Objective-C
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 44;
}
Swift 3
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44
}
tableView:heightForHeaderInSection:andtableView:heightForFooterInSection:set the header and footer heights. Returning only the header height leaves the footer at its default.
Objective-C
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 33;
}
Swift 3
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 33
}