我需要使用xib文件创建自己的UITableViewCell,以绘制图形界面...创建我的新类和用于我的UITableView的正确步骤是什么?
提前致谢
chr*_*oph 10
我个人认为这两个建议的教程都有一个很大的缺陷reuseIdentifier
.如果您忘记在界面构建器中分配它或拼错它,您将在每次cellForRowAtIndexPath
调用时加载nib .
Jeff LaMarche在这篇博客文章中写到了这个以及如何修复它.除了reuseIdentifier
他使用与苹果文档中相同的方法加载自定义表 - 从Nib文件查看单元格.
阅读完所有这些文章后,我想出了以下代码:
编辑:如果你的目标是iOS 5.0及更高版本,你会想要坚持使用Duane Fields的答案
@interface CustomCellWithXib : UITableViewCell
+ (NSString *)reuseIdentifier;
- (id)initWithOwner:(id)owner;
@end
@implementation CustomCellWithXib
+ (UINib*)nib
{
// singleton implementation to get a UINib object
static dispatch_once_t pred = 0;
__strong static UINib* _sharedNibObject = nil;
dispatch_once(&pred, ^{
_sharedNibObject = [UINib nibWithNibName:NSStringFromClass([self class]) bundle:nil];
});
return _sharedNibObject;
}
- (NSString *)reuseIdentifier
{
return [[self class] reuseIdentifier];
}
+ (NSString *)reuseIdentifier
{
// return any identifier you like, in this case the class name
return NSStringFromClass([self class]);
}
- (id)initWithOwner:(id)owner
{
return [[[[self class] nib] instantiateWithOwner:owner options:nil] objectAtIndex:0];
}
@end
Run Code Online (Sandbox Code Playgroud)
UINib(在iOS 4.0及更高版本中可用)在这里用作单例,因为尽管reuseIdentifier
使用了该单元,但仍然会将单元重新初始化大约10次左右.现在cellForRowAtIndexPath
看起来像这样:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCellWithXib *cell = [tableView dequeueReusableCellWithIdentifier:[CustomCellWithXib reuseIdentifier]];
if (cell == nil) {
cell = [[CustomCellWithXib alloc] initWithOwner:self];
}
// do additional cell configuration
return cell;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
54184 次 |
最近记录: |