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

Boon Kiat Seah
Boon Kiat Seah
66,664 Points

How to add a Button Programmatically

This is the extra credit exercise on iOS Development > Build a Simple iPhone App > Making It Pretty

The code below cannot be compiled on iPhone Retina (4inch) iOS 6.1. On iOS 7.0, the build can compile but no button is seen. Can the expert help?

 UIImage *image = [UIImage imageNamed:@"background.png"];

    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

    [self.view insertSubview:imageView atIndex:0];


  UIButton *predictButton = [[UIButton alloc] initWithFrame:CGRectMake(20, 20, 280, 37)];

  predictButton = [UIButton buttonWithType:UIButtonTypeCustom];

  [predictButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

  UIImage *imageOff = [UIImage imageNamed:@"button_bg_off.png"];

  UIImage *imageOn = [UIImage imageNamed:@"button_bg_on.png"];

  [predictButton setBackgroundImage:imageOff forState:UIControlStateNormal];

  [predictButton setBackgroundImage:imageOn forState:UIControlStateSelected];

  [self.view addSubview:predictButton];

2 Answers

Amit Bijlani
STAFF
Amit Bijlani
Treehouse Guest Teacher

Check the name of the images and make sure you have added them to your project. If either of them are not true then you will not see the button.

Boon Kiat Seah
Boon Kiat Seah
66,664 Points

i've checked, it is still not working for me.

Amit Bijlani
Amit Bijlani
Treehouse Guest Teacher

Do you have an image view in your storyboard that could be hiding the button?