使用故事板和子类创建自定义的UITableViewCell

8

我创建了一个UITableViewCell的子类,我称之为DCCustomCell。这是DCCustomCell.h文件。

#import <UIKit/UIKit.h>

@interface DCCustomCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UILabel *title;
@property (weak, nonatomic) IBOutlet UILabel *date;
@property (weak, nonatomic) IBOutlet UILabel *price;

@end

所有属性都与我的 iPhone.storyboard 文件中的元素正确连接。

我还在 iPhone.storyboard 中选择了tableViewCell,并将单元格的标识符设置为 "CustomCell",类设置为 DCCustomCell

这是UITableViewController的 viewDidLoad 方法:

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    [self.tableView registerClass:[DCCustomCell class] forCellReuseIdentifier:@"CustomCell"];

    // Do any additional setup after loading the view, typically from a nib.
}

这是tableView:cellForRowAtIndexPath:方法:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"CustomCell";

    DCCustomCell *cell = (DCCustomCell *)[tableView dequeueReusableCellWithIdentifier:identifier];

    NSLog(@"%@" ,cell);

    cell.imageView.image = [UIImage imageNamed:@"info_button.png"];
    cell.title.text = @"Hello!";
    cell.date.text = @"21/12/2013";
    cell.price.text = @"€15.00";

    return cell;
}

问题在于imageView已经正确设置,但所有的标签都是空的。如果我将imageView属性名称更改为eventImageView,例如,则图像将不会被设置。 这是结果:
我无法弄清楚如何解决这个问题。
编辑:如果我删除
[self.tableView registerClass:[DCCustomCell class] forCellReuseIdentifier:@"CustomCell"];

viewDidLoad开始一切都正常。为什么?

4个回答

9
正如你所注意到的,当你移除它时它能够工作。
[self.tableView registerClass:[DCCustomCell class] forCellReuseIdentifier:@"CustomCell"];

只有在使用dequeueReusableCellWithIdentifier:indexPath:并且尚未在身份检查器中设置该单元格的自定义类时,才需要执行此操作。如果使用registerClass:forCellReuseIdentifier,则将使用initWithStyle:reuseIdentifier:初始化单元格,而不是initWithCoder:,从而破坏您在故事板中创建的连接。


1

你是否已将控件绑定到IBOutlet? 您可以尝试在Storyboard中直接将DCCustomCell设置为UITableviewCell的类。 然后,您需要在单元格中设置控件的outlets


0

首先,请仔细检查您的插座,确保所有标签都已连接并写好:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *identifier = @"CustomCell";

        DCCustomCell *cell = (DCCustomCell *)[tableView dequeueReusableCellWithIdentifier:identifier];

        if (cell == nil)
        {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DCCustomCell" owner:self options:nil];

            cell = [nib objectAtIndex:0];
        }
        NSLog(@"%@" ,cell);

        cell.imageView.image = [UIImage imageNamed:@"info_button.png"];

        cell.title.text = @"Hello!";

        cell.date.text = @"21/12/2013";

        cell.price.text = @"€15.00";

        return cell;
    }

0

尝试:

if (cell == null) {
    //create and initialize cell
}

之后

DCCustomCell *cell = (DCCustomCell *)[tableView dequeueReusableCellWithIdentifier:identifier];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接