UITableViewController是一个预定义的视图控制器,在iOS中用于显示表格视图。它提供了许多有用的功能,例如轻松实现数据源方法、自动管理滚动行为、处理行选择等等。使用它,您可以更快地创建表格视图,并且更容易地将它们与其他操作结合使用。常见的实现方法是子类化UITableViewController,实现必要的数据源方法和其他适用的委托方法,然后将控制器分配给表格视图。以下是一个基本的UITableViewController实现示例:
@interface MyTableViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate>
@end
@implementation MyTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
//设置表格视图数据源
self.tableView.dataSource = self;
//设置表格视图委托
self.tableView.delegate = self;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
}
cell.textLabel.text = [NSString stringWithFormat:@"Row %ld", indexPath.row];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"Selected row: %ld", indexPath.row);
}
@end