Create a simple table view app in xcode

Open Xcode and create a new Single View Application. For product name, use SimpleTableView and then fill out the Organization Name and Company Identifier with your customary values. Select iPhone for Devices.


Drag a table view inside the view controller.



Connect the table view's datasource and delegate by right-clicking on the Table View and dragging from the circle to the View Controller.



First, we have to create an array where the the data will be coming from. Inside "ViewController.m"'s interface, add the the line
@property (strong, nonatomic) NSArray *data;

Next, inside the method viewDidLoad we have to allocate the array. This is gonna be the value of each cell in the table.
 self.data = [[NSArray alloc] initWithObjects:@"Number 1",@"Number 2", @"Number3", nil];

Next, we have to add the delegate. Change this line of code
@interface ViewController ()
to
@interface ViewController () <UITableViewDataSource, UITableViewDelegate>

Next, we have to implement the delegate methods. Add the following lines of code inside the "ViewController.m"
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = @"cellId";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

if (!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}

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

return cell;
}

Build and Run the project, you should now be able to see a very simple table view.



You can download the source code of the SimpleTableView at my repository on bitbucket.

0 nhận xét:

Đăng nhận xét