2013-06-06 24 views
7

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

risposta

12

Dopo initWithCoder: è chiamato cella, viene creata la cella e ha le sue caratteristiche impostate. Ma le relazioni nell'XIB (le IBOutlet) sulla cella non sono ancora complete. Pertanto, quando si tenta di utilizzare mainLabel, si tratta di un riferimento nil.

Spostare il codice di stile al metodo awakeFromNib. Questo metodo viene chiamato dopo che la cella è stata creata e completamente configurata dopo aver disimballato XIB.

Problemi correlati