免费开源的iOS开发学习平台

UITableView详解:4-表视图创建示例

通过对UITableView对象的了解,我们可以得知,UITableView是由一个个的UITableViewCell单元格构成的,并且每个单元格中显示的数据都是通过其数据源对象来获取的。

本节的示例代码,创建了一个UITableView对象,并且添加到控制器View上。UITableView上的每个单元格数据,都是通过UITableView的数据源对象--控制器来获取的。

  • 创建一个Single View Application

  • 在ViewController.m文件中,设置该控制器类遵守UITableViewDataSource协议,并且添加一个UITableView类型的属性

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UITableView * tableView;
@end
  • 对tableView属性进行懒加载,设置表视图的属性
-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.dataSource = self; //设置数据源对象
    }
    return _tableView;
}
  • 把表视图添加到控制器view上
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
}
  • 实现UITableViewDataSource协议中的tableView: numberOfRowsInSection:方法,返回表视图中包含的单元格个数,这里我们选择添加20个单元格
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 20;
}
  • 实现tableView: cellForRowAtIndexPath:方法,创建每一个单元格,该方法会被反复调用20次,即创建20个单元格
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //初始化cell
    static NSString *cellID = @"cell";   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];  
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }   
    //获取随机数据
    NSString *text = [NSString stringWithFormat:@"%d", arc4random_uniform(1000000)];   
    //设值
    cell.textLabel.text = text;    
    return cell;
}

运行后,我们可以看到在屏幕上出现了UITableView视图,并且可以向上滑动。在该案例中,我们并没有对单元格的样式进行复杂的定制,只是带领大家学习掌握如何创建表视图,这是我们学习表视图的第一步。

示例代码

https://github.com/99ios/8.2.4