How to use TableView inside viewcontroller?

b3rge picture b3rge · Jul 8, 2013 · Viewed 17.6k times · Source

In the storyboard I have added a table view to my view controller, I have ctrl dragged the TableView to to the Viewcontroller and connected "delegate" and "datasource". In the (.h) file I have added <UITableViewDataSource,UITableViewDelegate> but when I run the app I just get a SIGABRT error (?) and the app crashes. What should I do?

Answer

Levent Yıldız picture Levent Yıldız · Jul 8, 2013

So far so good, you just have to implement UITableViewDataSource and UITableViewDelegate in your implementation file.

Required functions are as follows;

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [regions count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Number of rows is the number of time zones in the region for the specified section.
    Region *region = [regions objectAtIndex:section];
    return [region.timeZoneWrappers count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    // The header for the section is the region name -- get this from the region at the section index.
    Region *region = [regions objectAtIndex:section];
    return [region name];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"MyReuseIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:MyIdentifier]];
    }
    Region *region = [regions objectAtIndex:indexPath.section];
    TimeZoneWrapper *timeZoneWrapper = [region.timeZoneWrappers objectAtIndex:indexPath.row];
    cell.textLabel.text = timeZoneWrapper.localeName;
    return cell;
}

Here's the link for the Apple documentation