2015-02-11 67 views
1

我有一個自定義的UITableViewCell,我要覆蓋像下面的init方法:重寫自定義單元格initWithStyle方法,但它沒有被稱爲

-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { 

    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
    self.buttons = [[NSMutableArray alloc] initWithObjects:self.button1, self.button2,self.button3,self.button4, nil]; 
    self.labels = [[NSMutableArray alloc] initWithObjects:self.label1,self.label2,self.label3,self.label4, nil]; 
    NSLog(@"init done"); 
    return self; 
} 

我需要這個方法把我的按鈕和標籤在數組中。我使用下面的代碼創建單元格:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    FriendViewCell *cell = (FriendViewCell *)[tableView dequeueReusableCellWithIdentifier:@"friendCell" forIndexPath:indexPath]; 

} 

但是,init方法未被調用且數組爲零。不知道發生了什麼!我是否覆蓋了正確的方法?

回答

2

僅當您明確調用此初始值設定項時纔會調用該初始值設定項。如果你從一個筆尖/故事板加載你的單元格,它將不會被調用。

通常,我們覆蓋awakeFromNib方法來自定義從nib加載的單元格。

- (void)awakeFromNib { 
    [super awakeFromNib]; 

    self.buttons = [[NSMutableArray alloc] initWithObjects:self.button1, self.button2, self.button3, self.button4, nil]; 
    self.labels = [[NSMutableArray alloc] initWithObjects:self.label1, self.label2, self.label3, self.label4, nil]; 
} 

另外要注意的 - 而不是從button1創建buttons陣列,button2等您可以使用IBOutletCollection,例如

@property (nonatomic) IBOutletCollection NSArray *buttons; 

,並直接從Interface Builder的連接按鈕,但請注意,它不保留對象的任何特定的順序。

+0

我需要保持訂購按鈕,有沒有辦法從故事板調用自定義的init方法呢? – Kex 2015-02-11 09:35:23

+0

@Kex不是'init'方法。使用'awakeFromNib'。 – Sulthan 2015-02-11 09:48:41

+0

謝謝你,現在正在工作 – Kex 2015-02-11 10:13:47

-2

您可以嘗試使用- (id)initWithCoder:(NSCoder *)aDecoder

還要確保你沒有忘記在界面生成器中設置單元格的自定義類(我假設你在IB中定義了自定義單元格)。

+0

這是行不通的。在'initWithCoder:'網點還沒有連接。 – Sulthan 2015-02-11 09:51:54

相關問題