从nib加载UITableViewCell的特殊方式



这是我发明的一种加载自定义单元格的方法

1) 我使用UITableViewCell类扩展

//.h
@interface UITableViewCell (Extended)
+ (id) cellWithClass:(Class)class;
+ (id) cellWithClass:(Class)class fromNibNamed:(NSString *)nibName;
@end
//.m
+ (id) cellWithClass:(Class)class
{
    return [UITableViewCell cellWithClass:class fromNibNamed:NSStringFromClass(class)];
}
+ (id) cellWithClass:(Class)class fromNibNamed:(NSString *)nibName {
    NSArray * nibContents = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:NULL];
    NSEnumerator * nibEnumerator = [nibContents objectEnumerator];
    NSObject * nibItem = nil;
    while ((nibItem = [nibEnumerator nextObject]) != nil) {
        if ([nibItem isKindOfClass:class]) {
            return nibItem;
        }
    }
    return nil;
}

2) 创建自定义UITableViewCell子类,使用相同名称的.nib(CustomCell.xib),其中我有连接的所有出口

@interface CustomCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel * labelSmth;
- (void) setupWithTitle:(NSString *)title;
@end

2) 在CustomCell.xib中,我使用接口生成器拖动UITableViewCell,并使其成为CustomCell的类(具有重用标识符CustomCell)(我不设置文件所有者)。。。以及UI样式、连接插座等。

3) 而不是像这个一样加载

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identifier = @"CustomCell";
    CustomCell * cell = [self.tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [UITableViewCell cellWithClass:[CustomCell class]];
    }
    [CustomCell setupWithTitle:[self.titles objectAtIndex:[indexPath row]]];
    return cell;
}

*这种方法可以吗?这对许多项目都有效,但我不确定重用器,也不确定单元格是否得到了正确的重用*

我也不确定这个

NSArray * nibContents = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:NULL];

当我在类方法中传递所有者self时。。。

苹果公司也提出了

- (void) registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)reuse;

这怎么能符合我的做法呢?

以及如何使用自定义重用标识符,比如如果我想要一个方法

+ (id) cellWithClass:(Class)class fromNibNamed:(NSString *)nibName reuseIdentifier:(NSString *)reuseIdentifier;

您不需要为此发明一些新东西。它已经为你发明了。你发明的是一种常见的反模式,用于加载自定义单元格。

枚举nib内容以获取nib中的UITableViewCell不是正确的方法。

您应该在创建UITableViewCell的nib(通常是UIViewController)的文件所有者中定义并导出到UITableViewCell。

然后你可以使用以下模式访问该单元格:

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    
    static NSString *cellIdentifier = @"MyCustomCell"; //this should also be specified in the properties of the UITableViewCell in the nib file
    MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if(!cell) {
        [[NSBundle mainBundle] loadNibNamed:cellIdentifier owner:self options:nil];
        cell = self.myCustomCellOutlet;
        self.myCustomCellOutlet = nil;
    }   
    return cell;
}

最新更新