2013-06-06 4 views
7

カスタムUITableViewCellにいくつかの問題があり、ストーリーボードを使って物事を管理する方法があります。私はinitWithCoder:にスタイリングコードを入れても機能しませんが、もしそれをtableView: cellForRowAtIndexPath:に入れれば動作します。ストーリーボードでは、クラス属性がUITableViewCellカスタムクラスに設定されたプロトタイプセルがあります。今度はinitWithCoder:のコードが呼び出されます。私は、コードをデバッグし、dequeue...が最初に呼び出されることを見出したinitWithCoderでカスタムUITableViewCellをスタイリングする:動作しない

- (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; 
} 

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は、それはその後、initWithCoder:とに入りますビューコントローラコードに戻ります。奇妙なことは、メモリ内のセルのアドレスがreturn self;の間で変化し、それがコントローラに戻るときです。そして、もし私がdequeue...の後にスタイル・コードをView Controllerに戻すと、すべて正常に動作します。ただ、私は細胞を再利用するときに不必要なスタイリングをしたくありません。 initWithCoder:

乾杯

答えて

12

は、セルが作成され、そのプロパティが設定されている、セルの上に呼ばれています。しかし、セル上のXIB(IBOutlets)の関係はまだ完全ではありません。したがって、mainLabelを使用しようとすると、nilの参照です。

スタイリングコードを代わりにawakeFromNibメソッドに移動します。このメソッドは、XIBを展開した後にセルが作成され、完全に構成された後に呼び出されます。

関連する問題