一:首先明确你要将这个UITalbeView应用到哪个View当中!
二:明确委托和协议机制!
三:明白什么是延迟加载(懒加载)!
四:确定展示的数据的储存方式,即明确储存数据结构!
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong, nullable)NSArray *arr1;
@property (nonatomic, strong, nullable)NSArray *arr2;
@end
A:首先在ViewController中添加如下属性:
1.声明一个UITableView *tableView,这个是今天的主角!
2.arr1和arr2是数据存储结构(为了举例子,使用简单的字符串数组,后面还会介绍使用字典等数据结构作为储存数据结构)
3.第一行,就是协议机制,遵循UITableViewDataSource 和 UITableViewDelegate协议,这两个协议中的必要接口功能,需要 ViewController自行实现,为后面系统的调用做准备。
- (void)viewDidLoad {
[super viewDidLoad];
self.digitalArr = @[@"0", @"1", @"2"];
self.letterArr = @[@"A", @"B", @"C"];
// 添加tableView到self.view
[self.view addSubview:self.tableView];//将tableView添加到某个view中
}
B:在加载函数中我们应该做些什么呢?
1.先向数据结构储存对象中储存一些简单的内容
2.[self.view addSubview:self.tableView];
首先我们执行self.tableView,这是一个函数,其函数体实现如下:
- (UITableView *)tableView {
if (_tableView == nil) {
// 实例化一个UITableView
_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, TABLE_WIDTH, TABLE_HEIGHT)
style:UITableViewStylePlain];
// 注册一个cell
[_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"myCell"];
// 设置代理
_tableView.delegate = self;
_tableView.dataSource = self;
}
return _tableView;
}
1⃣️这个_tableView只能初始化一次,
2⃣️注册一个cell !
3⃣️设置代理和数据源,即if条件体内的最后两行
然后我们已经初始化完成UITableView这一层面,于是我们将它加载到我们希望的View当中,调用addSubview函数。
C:然后做完了上层的工作,现在要处理cell了
该函数是协议中必须要实现的之一,返回得失每个section中cell的数量
// 对应Section中cell的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
switch (section) {
case 0: // 数字组
return self.digitalArr.count;
break;
case 1: // 字母组
return self.letterArr.count;
break;
default:
break;
}
return 0;
}
实例化一个UITableViewCell,做内容的存放,
// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell" forIndexPath:indexPath];
// 设置cell相关属性
switch (indexPath.section) {
case 0: // 数字组
if (indexPath.row < self.arr1.count) {//说明还有数据没有加载到tableview中
cell.textLabel.text = self.arr1[indexPath.row];
}
break;
case 1: // 字母组
if (indexPath.row < self.arr2.count) {
cell.textLabel.text = self.arr2[indexPath.row];
}
break;
default:
break;
}
// 返回cell
return cell;
}
D:当我们要更新数据的时间
[tableview reloadData];