2013-02-28 109 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: