Ho alcuni problemi con un UITableViewCell personalizzato e come gestire le cose usando gli storyboard. Quando inserisco il codice di stile in initWithCoder:
, non funziona, ma se lo inserisco in tableView: cellForRowAtIndexPath:
funziona. Nello storyboard ho una cella prototipo con il suo attributo di classe impostato sulla mia classe personalizzata UITableViewCell. Ora viene chiamato il codice initWithCoder:
.Styling personalizzato UITableViewCell in initWithCoder: non funziona
SimoTableViewCell.m
@implementation SimoTableViewCell
@synthesize mainLabel, subLabel;
-(id) initWithCoder:(NSCoder *)aDecoder {
if (!(self = [super initWithCoder:aDecoder])) return nil;
[self styleCellBackground];
//style the labels
[self.mainLabel styleMainLabel];
[self.subLabel styleSubLabel];
return self;
}
@end
TableViewController.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"NearbyLandmarksCell";
SimoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
//sets the text of the labels
id<SimoListItem> item = (id<SimoListItem>) [self.places objectAtIndex:[indexPath row]];
cell.mainLabel.text = [item mainString];
cell.subLabel.text = [item subString];
//move the labels so that they are centered horizontally
float mainXPos = (CGRectGetWidth(cell.contentView.frame)/2 - CGRectGetWidth(cell.mainLabel.frame)/2);
float subXPos = (CGRectGetWidth(cell.contentView.frame)/2 - CGRectGetWidth(cell.subLabel.frame)/2);
CGRect mainFrame = cell.mainLabel.frame;
mainFrame.origin.x = mainXPos;
cell.mainLabel.frame = mainFrame;
CGRect subFrame = cell.subLabel.frame;
subFrame.origin.x = subXPos;
cell.subLabel.frame = subFrame;
return cell;
}
Ho il debug del codice e ha scoperto che il dequeue...
si chiama, poi va nella initWithCoder:
e poi torna al codice del controller della vista. Ciò che è strano è che l'indirizzo della cella in memoria cambia tra return self;
e quando torna al controller. E se sposto di nuovo il codice di stile sul controller della vista dopo dequeue...
, tutto funziona correttamente. È solo che non voglio fare uno styling non necessario quando riusciamo le celle.
Acclamazioni