如何在 iOS 5 故事板中初始化自定义原型样式表单元格? [英] How to initialize a custom prototype style table cell in iOS 5 storyboards?

查看:14
本文介绍了如何在 iOS 5 故事板中初始化自定义原型样式表单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在转换到 iOS 5 和情节提要.当我有一个具有默认单元格样式的表格视图时,一切正常.

I am converting over to iOS 5 and storyboards. When I have a table view with default cell style, everything works fine.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifierFromStoryboard"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyIdentifierFromStoryboard"];
    }
    return cell;
}

我已经看到了删除if (cell == nil)"块的示例.但是,如果我将其取出,我的应用程序会崩溃并显示以下消息:UITableView 数据源必须从 tableView:cellForRowAtIndexPath: 返回一个单元格:".这不是问题,因为它的工作原理如上所示.

I have seen examples where the "if (cell == nil)" block is removed. However if I take it out, my app crashes with the message: "UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:". This is not a problem because it works as shown above.

我的问题是我想为单元格使用自定义样式,因此无法使用 initWithStyle.如何初始化我在情节提要上设计的自定义单元格?

My problem is that I want to use a custom style for the cell and thus cannot use initWithStyle. How do I initialize a custom cell that I have designed on the storyboard?

旧的 pre-5 应用有一个 nib 和 class 使用类似的东西,但现在我使用的是故事板.

The old pre-5 app had a nib and class that used something like this, but now I'm using the storyboard.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyCustomTableCell *cell = (MyCustomTableCell *) [tableView dequeueReusableCellWithIdentifier:@"MyCustomIdentifier"];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyCustomTableCell" owner:self options:nil];
        cell = (MyCustomTableCell *) [nib objectAtIndex:0];
    }
    return cell;
}

推荐答案

这样

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    return cell;
}

这篇关于如何在 iOS 5 故事板中初始化自定义原型样式表单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆