Since some people are stuck at some point while dynamically creating UITableView, this simple post will show you how to dynamically create UITableView in your iOS project
Lets say you wanna dynamically create a UITableView and show it on your app when you click a button.
First include necessary delegates in your header (.h) file
@interface DynamicTableTestViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
Then in your implementation (.m) file
You should include these required methods in your implementation file as defined under documentation of UITableView
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath;
Then when your button is clicked
- (IBAction)showTable:(id)sender {
if (dynamicTable==NULL) {
dynamicTable=[[UITableView alloc]initWithFrame:CGRectMake(10, 0, 300, 300)
style:UITableViewStylePlain];
style:UITableViewStylePlain];
dynamicTable.delegate=self;
dynamicTable.dataSource=self;
[self.view addSubview:dynamicTable];
}
}
Note: many people make this mistake. They assign the table.delegate to self and when they run the apps the tableview is not loaded with the data, then they are lost because many forget to assign table.dataSource to self.
No comments:
Post a Comment