[英]unable to set image on programmatically created UIButton in UITableViewCell
我有一个在情节提要中定义的自定义UITableViewCell,并且我正在以编程方式在每个单元格(在awakeFromNib中)中创建一个UIButton。 (用于重构的内容很多。)
我似乎无法在该按钮上设置图像。 该图像存在于资产目录中,我可以在其他(非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");
}
我敢肯定这是显而易见的。 请让我难堪。
问题出在这里。
[_heartButton setImage:[UIImage imageNamed:@"heart"] forState:UIControlStateNormal | UIControlStateHighlighted];
您必须按以下两条线设置那两个雕像。
[_heartButton setImage:[UIImage imageNamed:@"heart"] forState:UIControlStateNormal];
[_heartButton setImage:[UIImage imageNamed:@"heart"] forState:UIControlStateHighlighted];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.