Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMike Hoff
2,265 PointsProgrammatically adding button
I tried the extra credit in the video to programatically add a button. Two things I noticed and don't understand.
In the video in the story board the image property is set and not the background image. In code when I do this, all I get is a blue rectangle with no words on it, even though the image has the button title on it, so it appears not to be displaying it.
With my code when I press the button, the image shown is dim and not like the image file. What am I missing?
Here is my code:
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(30, 499, 261, 49);
UIImage *buttonImagePressed = [UIImage imageNamed:@"button-on"];
UIImage *buttonImageNormal = [UIImage imageNamed: @"button-off"];
[button setBackgroundImage:buttonImageNormal forState:UIControlStateNormal];
[button setBackgroundImage:buttonImagePressed forState:UIControlStateHighlighted];
[button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
6 Answers
Derek Medlin
6,151 PointsChange your buttonType to custom
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
Yumel Hernandez
11,902 Pointsi try to copy this into my code and I get an error saying. "Undeclared selector 'buttonPressed'".
Derek Medlin
6,151 PointsDo you have a button pressed method implemented?
- (void)buttonPressed {
NSLog(@"button was pressed");
}
Yumel Hernandez
11,902 Pointsyes, my button still does not appear on my simulator
Yumel Hernandez
11,902 Pointsi took that code and put it inside the buttonPressed method then i just called it on the viewDidLoad method
Derek Medlin
6,151 PointsIt's probably because you are running it in the 3.5 inch simulator and the y position for that button is 499. Just change it to where you can see it.
Mike Hoff
2,265 PointsMike Hoff
2,265 PointsThanks, that is what I needed to do, button images now work correctly using the setImage method or setBackgroundImage method. Thanks for the help!!