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
Nir Ohayon
2,399 PointsCreating a button programmatically (extra credit)
Hello,
This is my code:
UIButton *predictionButton = [[UIButton alloc] initWithFrame: CGRectMake(30, 480, 261, 49)];
[predictionButton addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
UIImage *buttonOn = [UIImage imageNamed:@"button-on"];
UIImage *buttonOff = [UIImage imageNamed:@"button-off"];
[predictionButton setBackgroundImage:buttonOff forState: UIControlStateNormal];
[predictionButton setBackgroundImage:buttonOn forState:UIControlStateHighlighted];
[self.view addSubview:predictionButton];
I have 2 questions:
Is it a good code for the task?
How should I use the documentation when giving a task like this?
What I did is I went to UIButton documentation and looked for something that will create a button, there was only 1 method "buttonWithType", which I didn't understand how to implement...and when I did kept to get errors, when I took it off and left the code above it worked.
please help
thanks
1 Answer
novall
3,397 PointsHere's an example of how you could implement buttonWithType:
- (void)viewDidLoad {
[super viewDidLoad];
[self addButton];
}
-(void)addButton {
UIButton *predictionButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[predictionButton addTarget:self action:@selector(addButton) forControlEvents:UIControlEventTouchUpInside];
[predictionButton setTitle:@"My Button" forState:UIControlStateNormal];
predictionButton.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[self.view addSubview:predictionButton];
}