【发布时间】:2012-07-17 09:56:34
【问题描述】:
这是我发明的加载自定义单元格的方法
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 中使用 Interface builder 我拖动一个 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];
当我在类方法中传递所有者自我时...
Apple 也想出了
- (void) registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)reuse;
这怎么可能适合我的方法?
以及如何使用自定义重用标识符,就像我想要一个方法一样
+ (id) cellWithClass:(Class)class fromNibNamed:(NSString *)nibName reuseIdentifier:(NSString *)reuseIdentifier;
【问题讨论】:
标签: ios objective-c uitableview cocoa-touch uikit