UITableView(表格)在实际开发中用得非常之多,下面将介绍它简单的使用方法:
表视图(UITableView 一讲)
1.定义:UITableView使用了重用机制,通过重用tableView的cell,达到节省内存的母的,使用一个字符串类型的ID判断是哪一种cell
2.UITableView是UIScrollView的子类,有两种样式 平铺和重组
3.初始化以及使用(它有两个重要的代理,基本上每次用的时候都会导入UITableViewDelegate,UITableViewDataSource):
UITableViewDataSource有两个必须实现的方法:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, margin, WIDTH, HEIGHT) style:UITableViewStylePlain];
tableView.delegate = self;
tableView.dataSource = self;
[self.view addSubview:tableView];
1⃣️:- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return dataList.count;
}
2⃣️: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
// cell的唯一标识
NSString *cellID = @"citys";
// UITableView 的重用 是通过查找cell的唯一标识cellID 来判断这个cell对象是否存在 如果不存在 再去实例化
// 通过cellID查找tableView上的cell dequeueReusable查找可重用的cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
// 如果没有查找到可重用的cell 就实例化cell对象
if (! cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
// cell.textLabel.text = dataList[indexPath.row]; 写在这里回引起数据混乱
// 不要再初始化cell的地方去加载数据 如果在这里加载 数据就会混乱
}
// 显示数据的时候 写在初始化cell的外面
// 不能在这个方法里面去加载初始化数据 因为这个会不断的调用
// 通过indexPath 得到哪一组(indexPat.section) 也可以得到是哪一行 (indexPath.row) 都是从 0 开始
cell.textLabel.text = dataList[indexPath.row];
cell.imageView.image = [UIImage imageNamed:@"wifi-full"];
return cell;
}
3⃣️:/**
* 选中cell的时候调用
*
* @param tableView
* @param indexPath
*/
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"%@",dataList[indexPath.row]);
UIAlertView *tishi = [[UIAlertView alloc]initWithTitle:nil message:@"ooo" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[tishi show];
}
UITableView简单使用方法
335

被折叠的 条评论
为什么被折叠?



