2013-02-28 111 views
4

我想創建一個自定義的UITableViewCell。創建一個自定義的UITableViewCell

從XCode 4.6界面構建器中,我已將單元格的Style屬性設置爲Custom。並使用拖放功能將控件添加到單元格中。 2個UILables和一個UIButton。它看起來像這樣。

enter image description here

我創建一個單獨的類從的UITableViewCell推導來分配3種UI元素的屬性,並進行相應的修改。我已經從Identity Inspector將單元的自定義類設置爲DashboardCell。

DashboardCell.h

DashboardCell.m

#import "DashboardCell.h" 

@implementation DashboardCell 

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 
{ 
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
    if (self) { 
     [self.numberOfOverdueMails setBackgroundColor:[UIColor colorWithRed:244/255.0f green:119/255.0f blue:125/255.0f alpha:1.0f]]; 
     [self.numberOfOverdueMails setTitle:@"lol" forState:UIControlStateNormal]; 
    } 
    return self; 
} 

- (void)setSelected:(BOOL)selected animated:(BOOL)animated 
{ 
    [super setSelected:selected animated:animated]; 

    // Configure the view for the selected state 
} 

@end 

在TableViewController,我已經修改了下面的方法來恢復我的自定義單元格。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    DashboardCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 
    if (cell == nil) { 
     cell = [[DashboardCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 

    return cell; 
} 

我的問題是,即使自定義按鈕顯示了,我已經做了改變(改變按鈕的背景顏色,改變一個的UILabel的標題)沒有顯示出來。這裏似乎有什麼錯誤?

回答

4

將不會調用方法initWithStyle:reuseIdentifier:,因爲您正在使用界面構建器來創建單元格。

您可以通過重寫方法awakeFromNib.

您還可以設置這些的方法tableView:cellForRowAtIndexPath:

2

如果你從廈門國際銀行或故事板的細胞,dequeueReusableCellWithIdentifier:forIndexPath:將始終返回設置背景顏色和標題單元格 - 如果存在,它將重新使用它,如果不存在,它將從IB中的模板創建一個單元格。因此,您的if(cell ==nil)條款將永遠不會滿足,事實上不再需要。如果您想使用init方法,則使用initWithCoder: