自定义UITableViewCell未加载

dar*_*sky 0 iphone objective-c uitableview ios

我正在使用界面构建器创建自己的自定义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
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

当我用以下代码替换loadBundle行时cell = [[CategoryCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];,它确实有效.但是笔尖没有加载.所以一个单元格加载,但不是我自己的单元格,所以我无法设置我想要的标签和图像.添加常规负载束线(如上面的示例所示)并断开init自定义单元格的方法时,不会调用它.另外,我得到的是全白屏幕,它覆盖了模拟器中的整个iPhone屏幕.

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

编辑:

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

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

我用NSBundle方法做错了什么?据说这应该是"更容易"的方式.

Vin*_*ent 6

你有没有在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
}
Run Code Online (Sandbox Code Playgroud)

确保你在CategoryCell.nib中有定义标识符,它位于属性检查器下!希望这项工作.