UITableView相当于Android里面的ListView,但功能却比ListView强大太多。
使用UITableView需要指定数据源和代理。
1.显示所有的行
遵守UITableViewDataSource协议,必须实现的方法有两个:
// 每一节里面有多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
// 每行的View,这里是UITableViewCell
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
2.修改每行高度选中行
遵守UITableViewDelegate协议
// 选中某行
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
// 设置每行高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
3.编辑模式
UITableView设置编辑模式可以(滑动)删除、添加和移动每一行。只需要修改其属性editing
@property(nonatomic,getter=isEditing) BOOL editing;
需要实现的方法
// 删除需要实现方法
- (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
// 移动需要实现的方法
- (void) tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
4.性能优化
首先根据Identifier从可重用的队列中拿,如果没有再重新分配Cell的内存。
static NSString *ID =@"tableview";
UITableViewCell *cell = [tableViewdequeueReusableCellWithIdentifier:ID];
if (cell == nil) {
cell= [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitlereuseIdentifier:ID];
}
5.例子
Shop.h
@interface Shop : NSObject
@property (nonatomic, copy) NSString *icon;
@pr