今天学习了一个很重要很常用的控件,UITableView。可以直接创建它,也可以创建UITableViewController。因为刚开始学习表视图,所以我先创建UITableView来练习。
接着前面的项目,我修改分栏控制器的第二个书签页面,我创建了一个BookMarkViewController来自定义ViewController。然后我创建了一个表示图,并把它设置为BookMarkViewController的视图。
-(void)loadView{
//创建表视图
UITableView *table = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen]applicationFrame] style:UITableViewStylePlain];
self.view =table;
table.dataSource = self;
}
其中dataSource是数据源,是用来设置表视图中单元格的内容的。要设置表视图的数据源,必须实现数据源协议UITableViewDataSource里的代理方法。
//返回section中单元格的数量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 9;
}
上面是第一个代理方法,是用来设置section中单元格数量的。
//返回单元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
// tableView.tableHeaderView.textLabel.text = @"1";
// 定义一个静态标识符
static NSString *cellIdentifier = @"cell";
// 检查是否有空闲的单元格
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
// 创建单元格
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
// 给cell内容赋值
cell.textLabel.text = [NSString stringWithFormat:@"%d只鸭子",indexPath.row];
return cell;
}
第二个代理方法是返回单元格的,我们要设置单元格的内容。因为加入有很多内容需要很多单元格显示,就很耗硬件资源。所以创建单元格时,先检查有没有空闲的单元格,有的话直接利用,没有的话才创建新的。屏幕滑动过了,部分单元格不显示了,就释放,使其成为空闲单元格,继续利用。
协议里除了上面两个必须要实现的方法外,还有其他的方法。比如可以设置section数量的方法numberOfSectionsInTableView,设置单元格header标题的tableView:titleForHeaderInSection:方法。
//返回section的数量
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 3;
}
//为section的header设置标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return [NSString stringWithFormat:@"第%d个",++section];
}
最后,运行程序,点击“书签”栏。
运行结果截图: