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

 孔红MJ 发布于 2023-02-13 19:41

我已经创建了一个子类,UITableViewCell并且我调用了它DCCustomCell.这是DCCustomCell.h文件.

#import 

@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文件中的元素正确连接.我还选择了tableViewCell,iPhone.storyboard并将我的单元格标识符设置为"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一切似乎工作.为什么?

1 个回答
  • 正如您所注意到的那样,当您移除时

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

    如果您使用dequeueReusableCellWithIdentifier:indexPath:AND尚未在该单元的标识检查器中设置自定义类,则只需执行此操作.如果您使用registerClass: forCellReuseIdentifier该单元格将被初始化,initWithStyle:reuseIdentifier:而不是initWithCoder:因此搞砸了您在故事板中所做的连接.

    2023-02-13 19:43 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有