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>
@interface
Instantiating_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
{
[
super
viewDidLoad
];
self
.
view
.
backgroundColor
=
[
UIColor
whiteColor
];
self
.
myTableView
=
[[
UITableView
alloc
]
initWithFrame:
self
.
view
.
bounds
style:
UITableViewStylePlain
];
[
self
.
view
addSubview:
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:
UITableViewStylePlain
Creates a plain table view with no background images.
UITableViewStyleGrouped
Creates a table view with a background image and rounded group borders, similar to the Settings app.
If you run your app right now on the iPhone Simulator, you will see the table view sitting there with no table view cells populated inside it (Figure 4-1).
Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.