我有一个在故事板中定义的自定义UITableViewCell,我以编程方式在每个单元格中创建一个UIButton(在awakeFromNib中)。 (重构太多了。)
我似乎无法在该按钮上设置图像。图像存在于资产目录中,我可以在其他(非tableview)视图中的按钮上设置它。并且按钮已正确创建并正常工作。但是图像没有出现,当我暂停模拟器并检查爆炸视图时,按钮在侧边栏中显示“无图像”。我有点难过。
相关代码(来自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");
}
我确信这是非常明显的。请让我难堪。
答案 0 :(得分:3)
问题出在这里。
[_heartButton setImage:[UIImage imageNamed:@"heart"] forState:UIControlStateNormal | UIControlStateHighlighted];
你必须将这两个雕像设置为两行,如下所示。
[_heartButton setImage:[UIImage imageNamed:@"heart"] forState:UIControlStateNormal];
[_heartButton setImage:[UIImage imageNamed:@"heart"] forState:UIControlStateHighlighted];