-
Notifications
You must be signed in to change notification settings - Fork 14
Using UITableView
Table views are the center of many iOS applications and have many features to customize their appearance and behavior. The sections below cover basic as well as more custom table views.
Download the sample code here.
Create a view controller with a xib, and drag a UITableView into the view, as shown below.
Control-drag from the nib to the implementation file to create an outlet to the UITableView, as shown below.
In the header file, declare that the class implements the table view datasource and delegate protocols.
@interface MainViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
...
@end
In viewDidLoad, configure the datasource and delegate of the table view.
- (void)viewDidLoad
{
[super viewDidLoad];
self.tableView.dataSource = self;
self.tableView.delegate = self;
}
There are many table view methods, but the only required methods are to set the number of rows for the table view and to return the cell for each row.
#pragma mark - Table view methods
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 5;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
cell.textLabel.text = [NSString stringWithFormat:@"This is row %d", indexPath.row];
return cell;
}
In practice, a UITableViewCell is rarely appropriate for your table views. Instead, you'll often need to create a custom cell with different subviews and custom highlight and selection effects. To create and use a custom cell, follow the steps below.
This video demonstrates the process of creating a custom cell using XCode 5.1: Custom Cell Video Walkthrough
- (void)viewDidLoad {
[super viewDidLoad];
UINib *movieCellNib = [UINib nibWithNibName:@"YourCustomCell" bundle:nil];
[self.tableView registerNib:movieCellNib forCellReuseIdentifier:@"YourCustomCell"];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
YourCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YourCustomCell" forIndexPath:indexPath];
return cell;
}