gpt4 book ai didi

ios - 从 nib 加载 UITableViewCell 的特殊方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:14:39 25 4
gpt4 key购买 nike

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

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),其中我连接了所有 socket

@interface CustomCell : UITableViewCell

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

- (void) setupWithTitle:(NSString *)title;

@end

2) 在 CustomCell.xib 中使用界面生成器我拖动一个 UITableViewCell 并使其成为 CustomCell 的类(具有重用标识符 CustomCell)(我不设置文件所有者)...然后进行 UI 样式设置、连接 socket 等...

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

*这种方法可行吗?这适用于许多项目,但我不确定 reuseidentfier 以及单元是否得到正确重用的事实...... *

我也不确定

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

当我在类方法中传递 owner self 时......

苹果也想出了

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

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

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

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

最佳答案

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

枚举 nib 内容以获取 nib 中的 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;
}

关于ios - 从 nib 加载 UITableViewCell 的特殊方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11520093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com