自定义单元格ios
当苹果公司提供给的单元格样式不能咱们的业务需求的时候,咱们须要自定义单元格。在iOS 5以前,自定义单元格能够有两种实现方式:代码实现和用xib技术实现。用xib技术实现相对比较简单,建立一个xib文件,而后定义一个继承 UITableViewCell类单元格类便可。在iOS 5以后咱们又有了新的选择,故事板实现方式,这种方式比xib方式更简单一些。ide
咱们把简单表视图案例的原型图修改一下,这种状况下四种内置的单元格样式就不合适了。布局
采用“Single View Application”工程模版建立一个名为“CustomCell”的工程,Table View属性的“Prototype Cells”项目设为1(除此以外其它的操做过程与上同)。atom
设计画面中上部会有一个单元格设计画面,咱们能够在这个位置进行单元格布局的设计。从对象库拖拽一个Label和Image View到单元格设计画面,调整好它们的位置。spa
建立自定义单元格类CustomCell, 选择UITableViewCell为父类设计
再 回到IB设计画面,在IB中左边选择“Table View Controller Scene” → “Table View Controller” → “Table View” → “Table View Cell”,打开单元格的标识检查器,在Class的选项中选择CustomCell类。对象
为Lable和ImageView控件链接输出口继承
本案例的代码以下:get
- //
- // CustomCell.h
- // CustomCell
- #import <UIKit/UIKit.h>
- @interface CustomCell : UITableViewCell
- @property (weak, nonatomic) IBOutlet UILabel *name;
- @property (weak, nonatomic) IBOutlet UIImageView *p_w_picpath;
- @end
- //
- // CustomCell.m
- // CustomCell
- #import “CustomCell.h”
- @implementation CustomCell
- @end
CustomCell类的代码比较简单,在有些业务中还须要定义动做。原型
修改视图控制器ViewController.m中的tableView: cellForRowAtIndexPath:方法,代码以下:
- - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
- {
- static NSString *CellIdentifier = @”Cell”;
- CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
- if (cell == nil) {
- cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
- }
- NSUInteger row = [indexPath row];
- NSDictionary *rowDict = [self.listTeams objectAtIndex:row];
- cell.name.text = [rowDict objectForKey:@"name"];
- cell.p_w_picpath.p_w_picpath = [UIImage p_w_picpathNamed:[rowDict objectForKey:@"p_w_picpath"]];
- NSUInteger row = [indexPath row];
- NSDictionary *rowDict = [self.listFilterTeams objectAtIndex:row];
- cell.textLabel.text = [rowDict objectForKey:@"name"];
- NSString *p_w_picpathPath = [rowDict objectForKey:@"p_w_picpath"];
- p_w_picpathPath = [p_w_picpathPath stringByAppendingString:@".png"];
- cell.p_w_picpath.p_w_picpath = [UIImage p_w_picpathNamed:p_w_picpathPath];
- cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
- return cell;
- }
咱们看到if (cell == nil){}代码被移除,这是由于咱们在IB中已经将重用标识设定为Cell了。 方法中的其它代码与简单表一致,此处再也不赘述。运行一下。