4.1. Populating a Table View with Data
Problem
You would like to populate your table view with data.
Solution
Conform to the UITableViewDataSource protocol in an object
and assign that object to the dataSource property of a table view.
Discussion
Create an object that conforms to the UITableViewDataSource protocol and assign it
to a table view instance. Then, by responding to the data source
messages, provide information to your table view. For this example,
let’s go ahead and declare the .m
file of our view controller, which will later create a table view on its
own view, in code:
#import "ViewController.h"staticNSString*TableViewCellIdentifier=@"MyCells";@interfaceViewController()<UITableViewDataSource>@property(nonatomic,strong)UITableView*myTableView;@end
The TableViewCellIdentifier contains our cell
identifiers as a static string variable. Each cell, as you will learn
soon, can have an identifier, which is great for reusing cells. For now,
think about this as a unique identifier for all the cells in our table
view, nothing more.
In the viewDidLoad method
of our view controller, we create the table view and assign our view
controller as its data source:
-(void)viewDidLoad{[superviewDidLoad];self.myTableView=[[UITableViewalloc]initWithFrame:self.view.boundsstyle:UITableViewStylePlain];[self.myTableViewregisterClass:[UITableViewCellclass]forCellReuseIdentifier:TableViewCellIdentifier];self.myTableView.dataSource=self;/* Make sure our table view resizes correctly ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access