Friday, June 7, 2013

UITableView initWithFrame example in Objective C (iOS).


UITableView initWithFrame

Initializes and returns a table view object having the given frame and style.

- (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style

Parameters
frame
A rectangle specifying the initial location and size of the table view in its superview'€™s coordinates. The frame of the table view changes as table cells are added and deleted.
style
A constant that specifies the style of the table view. See “Table View Style” for descriptions of valid constants.

Return Value of [UITableView initWithFrame]
Returns an initialized UITableView object or nil if the object could not be successfully initialized.

Discussion of [UITableView initWithFrame]
You must specify the style of a table view when you create it and you cannot thereafter modify the style. If you initialize the table view with the UIView method initWithFrame:, the UITableViewStylePlain style is used as a default.

UITableView initWithFrame example.
UITableView * aTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
aTableView.dataSource = aDataSource;
Note that you can't just set mainView to your tableView and expect it to work. mainView is an ivar or a local variable representing a view, changing it just changes the ivar, it doesn't actually attach or detach any views in the view hierarchy. In order to do that you you actually need to attaching it you using -[UIView addSubview:].

Example of [UITableView initWithFrame].
You cannot change the table view style like that. My advice use two tables or do something like this.

Initially it is like this:

tableObj= [[UITableView alloc]initWithFrame:CGRectMake(5,50,310,300)style:UITableViewStyleGrouped];
Then when you want to change do this:

[tableObj removeFromSuperView];
tableObj=nil;]
//if not using ARC
[tableObj release];
tableObj= [[UITableView alloc]initWithFrame:CGRectMake(5,50,310,300)style:UITableViewStylePlain];
[self.view addSubview:tableObj];

UITableView initWithFrame example.
-(void)setupTableView {
    tableViewInCell = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 132 , 320) style:UITableViewStylePlain];
    tableViewInCell.transform = CGAffineTransformMakeRotation(-M_PI * .5);
    tableViewInCell.frame = CGRectMake(0, 0, 320, 132);
    [tableViewInCell setDelegate:self];
    [tableViewInCell setDataSource:self];
    [self addSubview:tableViewInCell];

}

End of UITableView initWithFrame example article.