Objective c 创建自定义UITableViewCell

Objective c 创建自定义UITableViewCell,objective-c,uitableview,ios6,storyboard,custom-controls,Objective C,Uitableview,Ios6,Storyboard,Custom Controls,我正在尝试创建自定义UITableViewCell 在XCode 4.6 interface builder中,我将单元格的Style属性设置为Custom。并使用拖放将控件添加到单元格中。2个UILabel和一个UIButton。看起来像这样 我创建了一个从UITableViewCell派生的独立类,用于分配3个UI元素的属性并在其中进行更改。我还从Identity Inspector中将单元格的自定义类设置为DashboardCell 仪表板单元格.h #import <UIKit/

我正在尝试创建自定义UITableViewCell

在XCode 4.6 interface builder中,我将单元格的
Style
属性设置为Custom。并使用拖放将控件添加到单元格中。2个UILabel和一个UIButton。看起来像这样

我创建了一个从UITableViewCell派生的独立类,用于分配3个UI元素的属性并在其中进行更改。我还从Identity Inspector中将单元格的自定义类设置为DashboardCell

仪表板单元格.h

#import <UIKit/UIKit.h>

@interface DashboardCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UILabel *numberOfMails;
@property (weak, nonatomic) IBOutlet UILabel *mailType;
@property (weak, nonatomic) IBOutlet UIButton *numberOfOverdueMails;

@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的标题)也不会显示。这里的错误是什么?

将不会调用方法
initWithStyle:reuseIdentifier:
,因为您正在使用interface builder创建单元格

您可以通过覆盖方法awakeFromNib来设置背景色和标题。


您还可以在方法
tableView:cellForRowAtIndexPath:

中设置这些,如果您从xib或故事板获取单元格,
dequeueReusableCellWithIdentifier:forIndexPath:
将始终返回一个单元格——如果存在单元格,它将重用它,如果没有,它将从IB中的模板创建一个。因此,
If(cell==nil)
子句永远不会得到满足,事实上不再需要。如果要使用
init
方法,请使用
initWithCoder:

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