2

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

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];

当我在类方法中传递所有者自我时......

苹果也想出了

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

这怎么可能适合我的方法?

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

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

1 回答 1

3

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

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

您应该在您创建 UITableViewCell(通常是 UIViewController)的 nib 的文件所有者中定义和输出您的 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;
}
于 2012-07-21T20:25:28.327 回答