Friday, June 10, 2011

How to display the UITableView programmatically?

Add UITableView programmatically

Step 1.
In you file MyViewController.h

Add Protocols/ Delegates

@interface MyViewController : UITableViewController <UITableViewDelegate, UIAlertViewDelegate> {

UITableView *tableView;

}

Step 2:

Add following code in MyViewController.m file

-(void) viewDidLoad {



tableView = [[[UITableView alloc] initWithFrame:CGRectMake(0,0,320,480) style:UITableViewStylePlain] autorelease];
tableView.dataSource = self;
tableView.delegate = self;


[self.view addSubview:tableView];

}

// Default is 1 you can change as per your requirements.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

return 1;

}

// If there is more than one section then add check for section =0,1,2,3 and return accordingly

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

return [your array count];

}

// Add cell value from your array or static(As per requirements)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

}

// Configure the cell...

cell.textLabel.text = [yourarray objectAtIndex:indexPath.row];

return cell;

}

Above are 3 mandatory methods there are lots of other methods we can use as per our requirements.


1 comment:

Kamleshwar