4.1. Instantiating a Table View
Problem
You want to place a table view on your UI.
Solution
Instantiate an object of type UITableView and add it as a subview of any of
your views.
Discussion
There are two ways of instantiating a table view:
Through code
Using Interface Builder
If you are using Interface Builder, creating a table view is as
simple as dragging and dropping a table view from the object library
into your .xib file. If you are
more comfortable creating your components using code, then that is no
problem either. All you have to do is to instantiate an object of type
UITableView. Let’s start by defining
our table view in our view controller’s header file:
#import <UIKit/UIKit.h>@interfaceInstantiating_a_Table_ViewViewController:UIViewController@property(nonatomic,strong)UITableView*myTableView;@end
And creating the view controller is as easy as just allocating and
initializing an instance of UITableView:
-(void)viewDidLoad{[superviewDidLoad];self.view.backgroundColor=[UIColorwhiteColor];self.myTableView=[[UITableViewalloc]initWithFrame:self.view.boundsstyle:UITableViewStylePlain];[self.viewaddSubview:self.myTableView];}
The style parameter of the
initWithFrame:style: initializer of
the view controller allows us to specify what type of table view we
need. There are two styles that we can choose from:
UITableViewStylePlainCreates a plain table view with no background images.
UITableViewStyleGroupedCreates a table view with a background image and rounded group ...
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