views:

72

answers:

1

Hi!

So, I have a View Based Application where i want to add a UITableView but i don't know how i can do it. :/ thanks for your help !

A: 

In the XIB of the view, drag & drop a UITableView object.

In your .h, add the following code :

// the view controller implement the protocols of the UITableView
    @interface MyViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
    {
          IBOutlet UITableView *myTableView;    // Table view
          NSArray *myData;                      // Data to be displayed in the table
    }

@property (nonatomic, retain)  NSArray *myData; // property of the array

In your .m

@implementation MyViewController
@synthesize myData;

- (id)init
{
    self = [super init];
    self.myData = [[NSArray alloc] initWithObjects:@"Item 1", @"Item 2", nil];
    return self;
}

#pragma mark -
#pragma mark Table view data source

// Number of sections of the table
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    return 1;
}

// Number of lines in the table by section
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [myData count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{

    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        //
        // Create the cell.
        //
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleGray;

        //
        // Create the label for the top row of text
        //
        topLabel = [[[UILabel alloc] initWithFrame:cell.bounds] autorelease];
        topLabel.tag = 1;
        topLabel.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:topLabel];
    }
    else
    {
        topLabel = (UILabel *)[cell viewWithTag:1];

    }

    topLabel.text = [myArray objectAtIndex:indexPath.row];
}

#pragma mark -
#pragma mark Table view delegate

// Called when a cell was selected
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
// Do something
}

Go to IB.

Connect the UITableView to the Outlet (myTableView) you have created.

Connect the delegate & datasource properties of the UITableView to "File's Owner".

Then it should work.

EDIT:

do not forget to release myData in the dealloc function to avoir memory leak.

Niko