Friday, May 18, 2012

Creating a Table View in Xcode 4

//ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> {
NSArray *items; //items array to populate table view
}
@property (nonatomic, retain) NSArray *items;
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize items;
- (void)viewDidLoad
{
[super viewDidLoad];
//Allocated the memory for the array and initializing it with three string objects
items = [[NSArray alloc] initWithObjects:@"ONE", @"TWO", @"THREE", nil];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
#pragma mark - Table View Methods
//Return number of needed rows
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [items count];
}
//Allocate memory for the cells (table view rows)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Can we reuse a cell that is off screen?
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
//If no cell make a new one
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
}
//Add a detail view accessory
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
//Add cell text
cell.textLabel.text = [items objectAtIndex:indexPath.row];
return cell;
}

In your nib file, drag in a table view.
In your Nib file, connect the dataSource and delegate to the File's Owner

No comments:

Post a Comment

Blog Archive