关于UITableView的一点详解
(1)创建UITableView的方法有下面几种,使用storyboard,xib或者pure code,前面两种我不太熟悉,我一般用的是纯代码构建UITableView
(2)UITabelView最重要的两种协议dataSource和delegate
1.dataSource
这个是UITableView的数据源,涉及到列表的数据改动的协议都在这里面,比如:删除行,添加行,设置UITableViewCell的数据等等
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section; //设置行数
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; //设置cell里面的内容
2.delegate
这个是UITableView的一些行为规定,比如:点击行为,设置行高等等
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
(3)下面详述一下UITableView的具体实现
1.新建一个UITableView,并设置UITableView的dataSource和delegate,然后把她加到具体的view上面
UITableView *table = [[UITableView alloc] initWithFrame: [UIScreen mainScreen].bounds style: UITableViewStylePlain];
table.delegate = self;
table.dataSource = self;
[self.view addSubview: table];
2.设置delegate和dataSource的对象需要实现相应的协议
CollectionViewController.h文件实现
@interface CollectionViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
@end
CollectionViewController.m文件实现
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.items.count; //返回行数
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CollectionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[CollectionTableViewCell reuseIdentifier] forIndexPath: indexPath]; //自定义一个cell,需要注册一个class,重用标识符可以是改class的类名字符串
[cell setUpData: self.items[indexPath.row]]; //把数据传入cell中
return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 110; //返回行高
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//do something //选择某一行
}
基本上一个UITableView就简单实现了,当然,UITableView的很多方法没有讲到,感兴趣的同学可以自行去尝试。