创建自定义 UITableViewCell

Isu*_*uru 5 objective-c custom-controls storyboard uitableview ios6

我正在尝试创建一个自定义 UITableViewCell。

在 XCode 4.6 界面构建器中,我已将Style单元格的属性设置为自定义。并使用拖放向单元格添加控件。2 个 UILables 和一个 UIButton。它看起来像这样。

在此处输入图片说明

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

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

在 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;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是即使显示自定义按钮,我所做的更改(更改按钮的背景颜色,更改一个 UILabel 的标题)也没有显示。这里似乎有什么错误?

Osc*_*car 5

initWithStyle:reuseIdentifier:不会调用该方法,因为您正在使用界面构建器来创建单元格。

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

您也可以在方法中设置这些 tableView:cellForRowAtIndexPath: