自定义UITableViewCell未加载

时间:2012-11-24 22:23:30

标签: iphone objective-c ios uitableview

我正在使用界面构建器创建自己的自定义UITableViewCell。我支持iOS 5& iOS 6,但我不想使用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的视图。我按照必须连接插座。

问题

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];时,它确实有效。但是笔尖没有加载。所以一个单元格加载,但不是我自己的单元格,所以我无法设置我想要的标签和图像。添加常规负载包线(如上面的示例所示)并断开自定义单元格的init方法时,不会调用它。此外,我得到的是一个全白屏幕,它覆盖了模拟器中的整个iPhone屏幕。

为什么会这样?我在这做错了什么?当我尝试将出口设置为strong(我知道我不应该这样做)时,它也不起作用。

修改

我通过用以下代码替换NSBundle行来修复它:

UIViewController *temporaryController = [[UIViewController alloc] initWithNibName:@"CategoryCell" bundle:nil];
cell = (CategoryCell *)temporaryController.view;

我对NSBundle方法做错了什么?据说这应该是“更容易”的方式。

2 个答案:

答案 0 :(得分:6)

你有没有在tableview中尝试registerNib方法?从iOS 5开始加载笔尖非常方便。

- (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中有定义标识符,它位于属性检查器下!希望这项工作。

答案 1 :(得分:0)

  

XIB文件的类型为UIViewController,并且具有类型为CategoryCell的视图。我按照必须连接插座。

这个问题是你的XIB的根对象需要是UITableViewCell或它的子类。
并确保在您的XIB中设置重用标识符。

相关问题