似乎没有自定义单元格类是无法完成的。因为我们没有故事板原型单元格来为过滤后的表格视图进行图形化操作,所以我们必须以编程方式创建单元格。为此,我们需要一个自定义单元类,并在 .m 文件中使用 initWithStyle: 方法,如下所示。
所以我创建了一个名为 UITableViewCell 的 SelectionCell 子类的类,并在 IB 中将自定义单元格类分配给 SelectionCell 类,并将自定义单元格中的所有 UI 控件的 IBOutlet 创建到 SelectionCell.h 文件中
@interface SelectionCell : UITableViewCell{
}
@property (strong, nonatomic) IBOutlet UIImageView *contactPictureID;
@property (strong, nonatomic) IBOutlet UILabel *contactName;
@property (strong, nonatomic) IBOutlet UILabel *emailAddress;
@property (strong, nonatomic) IBOutlet UIImageView *selectedEmailState;
@end
在 initWithStyle: 方法中,我必须以编程方式重新创建所有 UI 控件并将它们作为子视图添加到 contentView:
// SelectionCell.m
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
self.selectionStyle = UITableViewCellSelectionStyleNone;
_contactPictureID = [[UIImageView alloc] initWithFrame:(CGRectMake(10, 14, 48, 48))];
_contactName = [[UILabel alloc] initWithFrame:(CGRectMake(66, 14, 201, 30))];
_contactName.font = [UIFont boldSystemFontOfSize:20];
_contactName.textAlignment = NSTextAlignmentLeft;
_emailAddress = [[UILabel alloc] initWithFrame:(CGRectMake(66, 41, 201, 21))];
_emailAddress.font = [UIFont systemFontOfSize:16];
_emailAddress.textAlignment = NSTextAlignmentLeft;
_selectedEmailState = [[UIImageView alloc] initWithFrame:(CGRectMake(275, 22, 32, 32))];
[self.contentView addSubview:_contactPictureID];
[self.contentView addSubview:_contactName];
[self.contentView addSubview:_emailAddress];
[self.contentView addSubview:_selectedEmailState];
}
return self;
}
现在我可以实例化我的自定义单元格了。在 cellForRowAtIndexPath 方法中
static NSString *CellIdentifier = @"SelectionCell";
SelectionCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[SelectionCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; }
现在一切正常。