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 trial

iOS Build a Simple iPhone App (iOS7) Designing your App Programming a Background Image

Mike Hoff
Mike Hoff
2,265 Points

Programmatically adding button

I tried the extra credit in the video to programatically add a button. Two things I noticed and don't understand.

  1. 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.

  2. 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

Change your buttonType to custom

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
Mike Hoff
Mike Hoff
2,265 Points

Thanks, that is what I needed to do, button images now work correctly using the setImage method or setBackgroundImage method. Thanks for the help!!

Yumel Hernandez
Yumel Hernandez
11,902 Points

i try to copy this into my code and I get an error saying. "Undeclared selector 'buttonPressed'".

Do you have a button pressed method implemented?

- (void)buttonPressed {
    NSLog(@"button was pressed");
}
Yumel Hernandez
Yumel Hernandez
11,902 Points

yes, my button still does not appear on my simulator

Yumel Hernandez
Yumel Hernandez
11,902 Points

i took that code and put it inside the buttonPressed method then i just called it on the viewDidLoad method

It'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.