`

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

本案例的代码如下:

//

//  CustomCell.h

//  CustomCell

#import <UIKit/UIKit.h>

@interface CustomCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UILabel *name;

@property (weak, nonatomic) IBOutlet UIImageView *image;

@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.image.image = [UIImage imageNamed:[rowDict objectForKey:@"image"]];

NSUInteger row = [indexPath row];

NSDictionary *rowDict = [self.listFilterTeams objectAtIndex:row];

cell.textLabel.text =  [rowDict objectForKey:@"name"];

NSString *imagePath = [rowDict objectForKey:@"image"];

imagePath = [imagePath stringByAppendingString:@".png"];

cell.image.image = [UIImage imageNamed:imagePath];

cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

return cell;

}

 

 

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

7

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics