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

自定义单元格

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

 

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

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

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

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

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

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

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

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

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

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

为Lable和ImageView控件连接输出口

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

本案例的代码如下:

 

  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 *p_w_picpath; 
  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.p_w_picpath.p_w_picpath = [UIImage p_w_picpathNamed:[rowDict objectForKey:@"p_w_picpath"]]; 
  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 *p_w_picpathPath = [rowDict objectForKey:@"p_w_picpath"]; 
  29.  
  30. p_w_picpathPath = [p_w_picpathPath stringByAppendingString:@".png"]; 
  31.  
  32. cell.p_w_picpath.p_w_picpath = [UIImage p_w_picpathNamed:p_w_picpathPath]; 
  33.  
  34. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
  35.  
  36. return cell; 
  37.  

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

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