UITableViewCell自定义cell

本文介绍两种在iOS开发中使用自定义UITableViewCell的方法。一种是通过UINib注册自定义cell,并在tableView中重用;另一种是在cell为空时加载nib文件创建实例。这两种方式都能有效地实现自定义cell的复用。

 

设计好自定义的cell并且连接好控件后  有两种方法引用我们自己的cell

 

方法1:

复制代码
 1 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 2 {
 3     static NSString *cellIdentifier=@"name";
 4     BOOL nibsRegistered=NO;
 5     if (!nibsRegistered) {
 6         UINib *nib=[UINib nibWithNibName:@"MyCell" bundle:nil];
 7        [tableView registerNib:nib forCellReuseIdentifier:cellIdentifier];
 8         nibsRegistered=YES;
 9     }
10     MyCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
11 //cell 上的元素初始化代码
12 
13 return cell;
14 }
复制代码
 UINib *nib=[UINib nibWithNibName:@"MyCell" bundle:nil];
[tableView registerNib:nib forCellReuseIdentifier:cellIdentifier];
这两句代码是引用我们自己定义的cell的关键 首先读取我们自己定义的cell的nib文件 再在tableView中注册 此时 我们定义的cell便加入
到了tableView的可重用队列当中了
MyCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
这句代码从中取出一个事例  然后初始化 并返回给tableView显示


方法2:
复制代码
 1 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 2 {
 3     static NSString *tableCellIdentifier = @"name";
 4     MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:tableCellIdentifier];
 5     
 6     if(cell == nil){
 7         NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"MyCell" owner:self options:nil];
 8         for(id oneObject in nib){
 9             if([oneObject isKindOfClass:[MyCell class]]){
10                 cell = (MyCell *)oneObject;
11             }
12         }
13     }
14     //cell初始化。。。
15     
16     return cell;
17 }
复制代码

转载于:https://www.cnblogs.com/shuxiachahu123/p/5008075.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值