iOS学习4_UITableView的使用

本文介绍了UITableView在iOS开发中的核心使用,包括显示所有行、自定义行高和选中效果、启用编辑模式以及性能优化策略。通过遵守UITableViewDataSource和UITableViewDelegate协议,实现数据源和代理方法。此外,还探讨了不同方式自定义单元格,如使用系统自带Cell、加载自定义XIB以及优化Cell复用。最后,提供了实现示例代码。
摘要由CSDN通过智能技术生成

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值