I have a custom UITableViewCell that's defined in a storyboard, and I'm programmatically creating a UIButton within each cell (in awakeFromNib). (So much for refactoring.)
I seem unable to set the image on that button. The image is present in an asset catalog and I'm able to set it on buttons in other (non-tableview) views. And the button is created properly and works properly. But the image does not appear, and when I pause the simulator and examine the exploded view, the button shows "no image" in the sidebar. I'm a bit stumped.
Relevant code (from the UITableViewCell subclass):
- (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");
}
I'm sure it's something terribly obvious. Please embarrass me.
The problem is in here.
[_heartButton setImage:[UIImage imageNamed:@"heart"] forState:UIControlStateNormal | UIControlStateHighlighted];
You have to set those two statues by two lines as below.
[_heartButton setImage:[UIImage imageNamed:@"heart"] forState:UIControlStateNormal];
[_heartButton setImage:[UIImage imageNamed:@"heart"] forState:UIControlStateHighlighted];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.