我正在使用界面生成器创建自己的自定义 UITableViewCell。我支持 iOS 5 和 iOS 6,但我不想使用 Storyboard。请不要建议 Storyboard。我坚持使用 Interface Builder 并以编程方式编写。
我创建了一个子类 UITableViewCell 的类。这是 .h 文件:
@interface CategoryCell : UITableViewCell
{
__weak IBOutlet UIImageView *image;
__weak IBOutlet UILabel *name;
__weak IBOutlet UILabel *distance;
__weak IBOutlet UILabel *number;
__weak IBOutlet UIImageView *rating;
}
@property (nonatomic, weak) IBOutlet UIImageView *image;
@property (nonatomic, weak) IBOutlet UILabel *name;
@property (nonatomic, weak) IBOutlet UILabel *distance;
@property (nonatomic, weak) IBOutlet UILabel *number;
@property (nonatomic, weak) IBOutlet UIImageView *rating;
@end
XIB 文件是 UIViewController 类型,有一个 CategoryCell 类型的 View 。我必须连接 socket 。
问题
dequeueResuableCellWithIdentifier
未调用自定义单元格。这是我拥有的:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"CategoryCell";
CategoryCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CategoryCell" owner:self options:nil];
cell = [topLevelObjects objectAtIndex:0];
.....
}
return cell
}
当我将 loadBundle
行替换为:cell = [[CategoryCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
时,它确实有效。但是 Nib 没有加载。所以加载了一个单元格,但不是我自己的单元格,所以我无法设置我想要的标签和图像。当添加常规加载包行(如上面的示例所示)和断点自定义单元格的 init
方法时,它不会被调用。此外,我得到的是覆盖模拟器中整个 iPhone 屏幕的全白屏。
为什么会这样?我在这里做错了什么?当我尝试将 socket 设置为 strong
(我知道我不应该这样做)时,它也不起作用。
编辑:
我通过将 NSBundle 行替换为以下内容来修复它:
UIViewController *temporaryController = [[UIViewController alloc] initWithNibName:@"CategoryCell" bundle:nil];
cell = (CategoryCell *)temporaryController.view;
我在 NSBundle 方法上做错了什么?据说这应该是“更简单”的方法。
最佳答案
你试过tableview中的registerNib方法吗?从 iOS 5 开始加载 nib 非常方便。
- (void)viewDidLoad
{
[super viewDidLoad];
[self.tableView registerNib:[UINib nibWithNibName:@"CategoryCell" bundle:nil]
forCellReuseIdentifier:@"CategoryCell"];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"CategoryCell";
CategoryCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
return cell
}
确保您在 CategoryCell.nib 中定义了标识符,它在属性检查器下!希望这项工作。
关于iphone - 自定义 UITableViewCell 未加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13546246/