Wednesday, April 21, 2010

Creating UIButton manually on IPhone SDK

Recently I started to learn iPhone development just for fun. iPhone sdk comes with great IDE which has great tool like memory leak finder, profiler, interface builder and other such tool. To create UI for iPhone application interface builder is great tool, but sometime we need to create control programatically at runtime. I also faced same situation to create UIButton control at runtime.

So here I am sharing my learning to create UIButton at runtime and adding it to view.

In following, I am creating UIButton named customButton, setting its location and size on screen and then image for normal and highlighted state.

UIButton* customButton = [UIButton buttonWithType:UIButtonTypeCustom];
[customButton setFrame:CGRectMake(10,10, 100, 100)];
[customButton setImage:[UIImage imageNamed:@"blue-ind.png"] forState:UIControlStateNormal];
[customButton setImage:[UIImage imageNamed:@"red-ind.png"] forState:UIControlStateHighlighted];
Then I am specify what function needed to be called when button get pressed using addTarget method of UIButton.

[customButton addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
Finally adding button to view.

[self.view addSubview:customButton];
Now when above button is clicked, btnClicked method will be get called. I have used following declaration and definition for btnClicked method.

-(void) btnClicked ;

-(void) btnClicked {
    NSLog(@"Custom button clicked");
}
Here is output of above code.



2 comments:

  1. im looking for the way to move controls at runtime, do you have any suggest?

    ReplyDelete
  2. you can use setFrame api to reposition control at runtime.

    ReplyDelete