您的位置:首页 > 产品设计 > UI/UE

UITableView:表视图

2015-09-16 22:42 274 查看
//UITableView:表视图
/* UITableView 使用重用机制(滚筒原理)
通过重用tableView的cell达到节省的目的
使用一个字符串类型的ID判断是那种cell

*****UITableView有两个必须实现的代理方法
在datasource 、Delegate
里面 (这是强制实现的方法
必须写 不然就崩溃)
状态栏的高度是20
UITableView 有两种样式
一种是平铺 另一种是分组
UITableView是UIScrollView的子类 UIScrollView的方法和属性UITableView都可以使用 */

#import "ViewController.h"
#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT CGRectGetHeight([UIScreen mainScreen].bounds)

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
{
NSArray *list;
}
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
list = @[@"东城区",@"西城区",@"宣武区",@"崇文区",@"朝阳区",@"海淀区",@"房山区",@"通州区",@"顺义区",@"昌平区",@"大兴区",@"怀柔区",@"平谷区",@"密云县",@"延庆县",@"门头沟区",@"石景山区"];

UITableView *mytableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 20, WIDTH, HEIGHT) style: UITableViewStylePlain];
mytableView.delegate = self;
mytableView.dataSource = self;//挂上这两个代理必须
实现他的方法
[self.view addSubview:mytableView];

// 在需要更新数据的时候
可以使用reloadData来更新数据
// 当咱们使用reloadData的时候 “所有代理方法”都会重新调用一次
用来更新数据

// UITableView的对象
去调用reloadData
// [mytableView reloadData];

}
// 在这个组里面有多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section // section层数(组)
{
// Section表示哪一组
如果是0表示0组 1表示1组
从0开始
return list.count;
}
//显示TableView的内容() TableView上的每一个横格都是一个UITableViewCell UITableView上面的数据
就是显示在每一个UITableViewCell上的 cellForRowAtIndexPath有多少行就会调用多少次
//原因:是它的返回值-UITableViewCell
需要提供给UITableView 它需要数量的cell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath//
{
// cell的唯一标识
NSString *cellID = @"cityCell";
// UITableView重用机制
是通过查找cell 的唯一标识cellID来判断这个cell对象是否存在
如果不存在 得去实例化对象

// 通过cellID查找tableView上的cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];//在这个列里面查找重用的cellID
// 如果没有查找到可重用的的cell
实例化cell对象
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
// 不要在初始化cell的地方去显示数据
否则数据会混乱 加载数据的时候
写在初始化的外面
// cell.textLabel.text = list[indexPath.row];//不能这么写
不能问发抄写10遍
}
// 加载显示数据写在外面
不能在这个方法里面去加载初始化数据 因为这个会不断的调用
//indexPath: 可以通过indexPath得到是哪一组(indexPath.section)
也可以得到是哪一行(indexPath.row)
都是从0开始
cell.textLabel.text = list[indexPath.row];
cell.imageView.image = [UIImage imageNamed:@"用户管理"];
return cell;
}
//选中cell的时候调用
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

NSLog(@"%@",list[indexPath.row]);

}

//设置没一行的行高

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 66;
}
//设置每组的头高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
return 60;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: