Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2613635
  • 博文数量: 877
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 5921
  • 用 户 组: 普通用户
  • 注册时间: 2013-12-05 12:25
个人简介

技术的乐趣在于分享,欢迎多多交流,多多沟通。

文章分类

全部博文(877)

文章存档

2021年(2)

2016年(20)

2015年(471)

2014年(358)

2013年(26)

分类: iOS平台

2015-08-24 10:49:02

http://www.cnblogs.com/bucengyongyou/archive/2012/09/02/2667330.html

对自定义UITableViewCell的理解

自定义UITableViewCell有两种方法:

1.较早版本 子类UITableViewCell   并利用xib构造

2.利用storyboard直接自定义cell

 

 

1.利用xib

设计好自定义的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 }
复制代码
 2.利用storyboard自定义cell 利用storyboard自定义cell比较简单   较xib 方法    少了读取xib文件的一步

在storyboard中拖出一个tableViewController后 拖上去一个cell  然后自己设计cell  最后一定要填上identifier
此时cell已经磨人添加到了tableview的  重用队列中了
引用的时候只需 
复制代码
1 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 2 { 3 //这个是在storyboard中设置的identifier 4 static NSString *tableCellIdentifier = @"name"; 5 MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:tableCellIdentifier]; 6 //cell初始化 7 return cell; 8 }
复制代码

 

 

纯属自己的一些理解  写下来方便自己记忆   如有错误指出 希望大家讨论指正

转载请著名出处

阅读(338) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~