无法在 UITableViewCell 中以编程方式创建的 UIButton 上设置图像

unable to set image on programmatically created UIButton in UITableViewCell

我有一个在故事板中定义的自定义 UITableViewCell,我正在以编程方式在每个单元格中创建一个 UIButton(在 awakeFromNib 中)。 (重构到此为止。)

我好像无法在该按钮上设置图像。该图像存在于资产目录中,我可以将其设置在其他(非表格视图)视图中的按钮上。并且按钮已正确创建并正常工作。但是图像没有出现,当我暂停模拟器并检查分解图时,按钮在边栏中显示 "no image"。我有点难过。

相关代码(来自UITableViewCell子类):

- (id)initWithCoder:(NSCoder *)aDecoder {
    if (self) {
        self = [super initWithCoder:aDecoder];
        viewsDict = [[NSMutableDictionary alloc] initWithCapacity:24]; // for constraints
    }
}

- (void)awakeFromNib {
    [super awakeFromNib];

    [self.contentView addSubview:self.heartButton]; // instantiates the button (see below)
    [[self.heartButton superview] bringSubviewToFront:self.heartButton];

    [viewsDict setObject:self.heartButton forKey:@"heartButton"];
    [viewsDict setObject:self.containerView forKey:@"containerView"];

    // constraints
    [self.heartButton addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[heartButton(32)]" options:0 metrics:nil views:viewsDict]];
    [self.heartButton addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[heartButton(32)]" options:0 metrics:nil views:viewsDict]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-8-[heartButton]" options:0 metrics:nil views:viewsDict]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[containerView][heartButton]" options:0 metrics:nil views:viewsDict]];
}

- (UIButton *)heartButton {
    if (_heartButton == nil) {
        _heartButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_heartButton setTranslatesAutoresizingMaskIntoConstraints:NO];
        SEL selector = NSSelectorFromString(@"heartButtonTapped:");
        [_heartButton addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
        [_heartButton setImage:[UIImage imageNamed:@"heart"] forState:UIControlStateNormal | UIControlStateHighlighted];
    }
    return _heartButton;
}

- (IBAction)heartButtonTapped:(id)sender {
    NSLog(@"This gets logged when the button gets tapped");
}

我敢肯定这是非常明显的事情。请为难我。

问题就出在这里

[_heartButton setImage:[UIImage imageNamed:@"heart"] forState:UIControlStateNormal | UIControlStateHighlighted];

你必须如下两行设置那两个雕像。

[_heartButton setImage:[UIImage imageNamed:@"heart"] forState:UIControlStateNormal];
[_heartButton setImage:[UIImage imageNamed:@"heart"] forState:UIControlStateHighlighted];