UITableViewCell的初始化位置在哪里?

时间:2014-02-13 19:52:15

标签: ios objective-c uitableview xib

我已经创建了自己的CustomTableViewCustomCell。单元格在xib中,我在初始化tableView时注册它,如下所示:

[self registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] 
                    forCellReuseIdentifier:kCustomCellIdentifier];

如果我不这样做,我就无法定义ReuseIdentifier应该"指向"到这堂课。这是我的cellForRow

-(UITableViewCell *)tableView:(UITableView *)tableView 
                        cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCell *cell = [self dequeueReusableCellWithIdentifier:
                        kCustomCellIdentifier forIndexPath:indexPath];

    if(!cell)
    {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"CustomCell" 
                        owner:self options:nil] objectAtIndex:0];

        cell.delegate = self;
        [cell initialSetup]; //Other stuff
    }
    else
        [cell resetCell];

    //And other awesome stuff

    return cell;
}

这个'工作'。当我浏览我的应用程序时,我自己的自定义单元格正在显示。 但是,事实证明,单元格永远不会从nil返回[self dequeue..。因此,if语句if(!cell)永远不会成立。我在此声明中有我想要执行的其他设置,但我不知道现在第一次初始化单元格的位置。如果我删除registerNib,那么这个陈述是正确的,但是对于所有单元格都是如此,并且没有一个会被出列。

我可以解决这个问题,并将我的initialSetup(以及其他内容)放在CustomCell类的-(id)initWithCoder.. - 方法中,但我想知道我的细胞在哪里现在正在初始化。为什么我的单元格在cellForRowAtIndexPath之前存在?

3 个答案:

答案 0 :(得分:2)

使用方法registerClass:forCellReuseIdentifierregisterNib:forCellReuseIdentifier在表视图中注册类或nib时,如果在调用{{1}时没有人可用,则tableview内部将创建单元格的实例因此,代理中不再需要初始化代码。

来自dequeueReusableCellWithIdentifier:代码:

UITableView.h

根据使用的// Beginning in iOS 6, clients can register a nib or class for each cell. // If all reuse identifiers are registered, use the newer -dequeueReusableCellWithIdentifier:forIndexPath: to guarantee that a cell instance is returned. // Instances returned from the new dequeue method will also be properly sized when they are returned. - (void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(5_0); - (void)registerClass:(Class)cellClass forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(6_0); 方法,调用的register方法是:

  • init表示使用initWithStyle:reuseIdentifier
  • 注册的单元格
  • registerClass:表示使用initWithCoder:
  • 注册的单元格

如果您使用的是registerNib:,则可以在单元格中使用registerNib:方法,这也是放置单元格初始化代码的好地方。使用awakeFromNibinitWithCoder:this question中解释的主要区别。

当一个单元格被重用时,你在单元格中使用方法awakeFromNib来对单元格进行一些清理,并准备再次进行配置。

使用所有这些的好方法是:

prepareForReuse

希望有所帮助

答案 1 :(得分:0)

使用dequeueReusableCellWithIdentifier: forIndexPath:时,您不必像使用默认UITableViewCell那样分配单元格。在您的自定义UITableViewCell子类中,在初始化时调用它:

- (void)awakeFromNib {
     [super awakeFromNib];
}

所以在那里加上你应该是好的。

答案 2 :(得分:0)

- (instancetype)initWithStyle:(UITableViewCellStyle)style
              reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
    //custom your cell
    }
    return self;
  }
相关问题