initWithFrame vs initWithStyle [英] initWithFrame vs initWithStyle

查看:197
本文介绍了initWithFrame vs initWithStyle的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从已弃用的 initWithFrame更新我的TableView:reuseIdentifier:

我的tableview使用自定义单元格。

My tableview uses custom cells.

它到处说它使用 initWithStyle:,并且它不会以任何方式改变行为或单元格从 initWithFrame:CGRectZero reuseIdentifier:

Everywhere it says to use initWithStyle:, and that it does not change behavior or the cell in any way from initWithFrame:CGRectZero reuseIdentifier:.

但是当我用构建initWithStyle时:UITableViewCellStyleDefault reuseIdentifier:单元格变为空白(即我们的自定义单元格不起作用(因为它是用某种样式初始化的?)。)

But when I am building with initWithStyle:UITableViewCellStyleDefault reuseIdentifier: the cells become blank (i.e. our custom cell does not work (because it is initialized with some style?)).

之后单元格已初始化(如果它没有出列),我们在单元格上设置文本。但是当我使用 initWithStyle:reuseIdentifier:时,这些都没有设置,但它适用于 initWithFrame:CGRectZero 。除了使用的init方法( initWithStyle )之外,没有任何代码被更改。

After the cell has been initialized (if it did not dequeue), we set texts on the cell. But these are not set when I use initWithStyle:reuseIdentifier: but it works with initWithFrame:CGRectZero. None of the code is changed except for the init method used (initWithStyle).

这些行放在单元格之后已创建(或重复使用):

These rows put in after cell is created (or reused):

cell.newsItemNameLabel.text = @"test";
NSLog(@"NewsItemName: %@",cell.newsItemNameLabel.text);

结果NewsItemName:(null)

Results in "NewsItemName: (null)"

有人有想法吗?两者之间真正的区别是什么?

Anybody has an idea? What is the real difference between the two?

谢谢

推荐答案

您的 cellForRowAtIndexPath 的实现应类似于以下内容:

Your implementation of cellForRowAtIndexPath should look similar to the following:

- (CustomCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CellIdentifier";

    CustomCell *cell = (CustomCell *)(UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // Configure the cell.
    cell.textLabel.text = NSLocalizedString(@"Detail", @"Detail");
    return cell;
}

其中 CustomCell 是自定义单元格类的名称。请注意,此实现使用ARC(自动引用计数)。如果您碰巧不使用此功能,请添加 autorelease 调用您的单元格分配。

where CustomCell is the name of your custom cell's class. Note that this implementation uses ARC (Automatic Reference Counting). If you don't happen to use this feature, add a autorelease call to the allocation of your cell.

CustomCell initWithStyle 实施:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        //do things
    }
    return self;
}

这篇关于initWithFrame vs initWithStyle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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