问题
I want to update my TableView from the deprecated initWithFrame:reuseIdentifier:
.
My tableview uses custom cells.
Everywhere it says to use initWithStyle:
, and that it does not change behavior or the cell in any way from initWithFrame:CGRectZero 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?)).
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);
Results in "NewsItemName: (null)"
Anybody has an idea? What is the real difference between the two?
Thank you
回答1:
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;
}
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
's initWithStyle
implementation:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
//do things
}
return self;
}
来源:https://stackoverflow.com/questions/9380710/initwithframe-vs-initwithstyle