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

iOS extra credit-adding a button programmatically

I'm having trouble adding the button programmatically. This is the only code I have. If someone could point me in the right direction, that would be great. Thanks!

    //Extra credit -- programming the button
    UIImage *buttonOff = [UIImage imageNamed:@"button-off.png"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:buttonOff];

    [self.view addSubview:imageView];

6 Answers

you need to adda button, not an image view. you have the right idea, instead of creating an imageView create a button and add it as a subview

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[self.view addSubview:button];

then you need to set a title, you can use the setTitle for control state method. it then needs to be sized to fit the text of its title, so call the sizeToFit method on it

[button setTitle:@"The title" forState:UIControlStateNormal];
[button sizeToFit];

By default this button wil be positioned at (0,0). you can position the button where you want it by changing its center property and assigning it a CGPoint:

button.center = CGPointMake(200, 200);

If you wanna make a button create a new instance of UIButton:

    UIbutton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

Check the documentation for the options available.

Thanks for the help, but there's still a few more problems. When I click the button it does not actually do anything or it "doesn't predict the future".

You need to call the add target action forControlEvent method

[button addTarget:self action:@selector(someMethod) forControlEvents:UIControlEventTouchUpInside];

Where someMethod is the method you want called when the button is pressed

So put the code that causes the prediction to be made into a method, and set that method as the selector

If you guys could help with one more thing, that would be awesome. How do I add constraints so that it works with a 3.5 inch iPhone? Thanks

Thanks for the help!!!