如何在viewcontroller中使用TableView?

b3r*_*rge 12 xcode objective-c storyboard uiviewcontroller tableview

在故事板中我向视图控制器添加了一个表视图,我将ctrl拖动到ViewController并连接到"delegate"和"datasource".在我添加的(.h)文件中,<UITableViewDataSource,UITableViewDelegate>但是当我运行应用程序时,我只收到SIGABRT错误(?)并且应用程序崩溃了.我该怎么办?

Lev*_*dız 20

到目前为止,您只需要在实现文件中实现UITableViewDataSource和UITableViewDelegate.

所需功能如下;

- (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;
}
Run Code Online (Sandbox Code Playgroud)

这是Apple文档的链接