Pages

Thursday, July 28, 2011

[Code Snippet] Add UIButton programatically

I have not so much time to update the blog, but I have to maintance the wednesday's code snippet so today's code snippet is about one of those things that are very easy to do, but difficult to remember: add a UIButton programatically to our view.

To add a basic UIButton programatically, just instance it, give it a frame and obviously a selector for the TouchInside (click) event, and that's all.

Code snippet is like that

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[myButton addTarget:self
           action:@selector(myButton_click:)
 forControlEvents:UIControlEventTouchDown];
[myButton setTitle:@"My title" forState:UIControlStateNormal];
myButton.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:myButton];

- (IBAction) myButton_click:(id)sender
{
    NSLog(@"Button clicked");
}

Good programming!!!!

No comments:

Post a Comment