iOS开发那些事--自定义单元格实现

自定义单元格

当苹果公司提供给的单元格样式不能我们的业务需求的时候,我们需要自定义单元格。在iOS 5之前,自定义单元格可以有两种实现方式:代码实现和用xib技术实现。用xib技术实现相对比较简单,创建一个xib文件,然后定义一个继承 UITableViewCell类单元格类即可。在iOS 5之后我们又有了新的选择,故事板实现方式,这种方式比xib方式更简单一些。

 

我们把简单表视图案例的原型图修改一下,这种情况下四种内置的单元格样式就不合适了。

  1

    采用“Single View Application”工程模版创建一个名为“CustomCell”的工程,Table View属性的“Prototype Cells”项目设为1(除此之外其它的操作过程与上同)。

 2

设计画面中上部会有一个单元格设计画面,我们可以在这个位置进行单元格布局的设计。从对象库拖拽一个Label和Image View到单元格设计画面,调整好它们的位置。

 3

创建自定义单元格类CustomCell, 选择UITableViewCell为父类

 4

再 回到IB设计画面,在IB中左边选择“Table View Controller Scene” → “Table View Controller” → “Table View” → “Table View Cell”,打开单元格的标识检查器,在Class的选项中选择CustomCell类。

 5

为Lable和ImageView控件连接输出口

 6

本案例的代码如下:

 

 
 
  1. // 
  2.  
  3. //  CustomCell.h 
  4.  
  5. //  CustomCell 
  6.  
  7. #import <UIKit/UIKit.h> 
  8.  
  9. @interface CustomCell : UITableViewCell 
  10.  
  11. @property (weak, nonatomic) IBOutlet UILabel *name; 
  12.  
  13. @property (weak, nonatomic) IBOutlet UIImageView *image; 
  14.  
  15. @end 
  16.  
  17. // 
  18.  
  19. //  CustomCell.m 
  20.  
  21. //  CustomCell 
  22.  
  23. #import “CustomCell.h” 
  24.  
  25. @implementation CustomCell 
  26.  
  27. @end 

CustomCell类的代码比较简单,在有些业务中还需要定义动作。

修改视图控制器ViewController.m中的tableView: cellForRowAtIndexPath:方法,代码如下:

 

 
 
  1. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
  2.  
  3.  
  4. static NSString *CellIdentifier = @”Cell”; 
  5.  
  6. CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
  7.  
  8.     if (cell == nil) { 
  9.  
  10.         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
  11.  
  12.     } 
  13.  
  14. NSUInteger row = [indexPath row]; 
  15.  
  16. NSDictionary *rowDict = [self.listTeams objectAtIndex:row]; 
  17.  
  18. cell.name.text =  [rowDict objectForKey:@"name"]; 
  19.  
  20. cell.image.image = [UIImage imageNamed:[rowDict objectForKey:@"image"]]; 
  21.  
  22. NSUInteger row = [indexPath row]; 
  23.  
  24. NSDictionary *rowDict = [self.listFilterTeams objectAtIndex:row]; 
  25.  
  26. cell.textLabel.text =  [rowDict objectForKey:@"name"]; 
  27.  
  28. NSString *imagePath = [rowDict objectForKey:@"image"]; 
  29.  
  30. imagePath = [imagePath stringByAppendingString:@".png"]; 
  31.  
  32. cell.image.image = [UIImage imageNamed:imagePath]; 
  33.  
  34. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
  35.  
  36. return cell; 
  37.  

我们看到if (cell == nil){}代码被移除,这是因为我们在IB中已经将重用标识设定为Cell了。 方法中的其它代码与简单表一致,此处不再赘述。运行一下。

7

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值