This is a simple programming approach to create and add a button on UIView dynamically. To create a button programmatically just follow the given steps...
This is a simple programming approach to create and add a button on UIView dynamically. To create a button programmatically just follow the given steps...Create UIButton Programmatically
In this example we'll discuss about how to create a UIButton in code.
This is a simple programming approach to create and add a button on UIView dynamically. To create a button programmatically just follow the given steps...
1. Create a UIButton with the type that your application req. like you can create a simple RoundedRect button or a custom button if need to set any image in the background.
Code
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
Set the button frame as given below to set the button size and position in the parent view.
myButton.frame = CGRectMake(80, 50, 150, 40);
Set the title of the button
[myButton setTitle:@"Say, Hi!" forState:UIControlStateNormal];
Now, add targets and action on the button. "buttonClicked" is the name of the button action that we need to declare in both .h and .m ViewControllers.
[myButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
So far, we have successfully create a button but to add this button on view we need to write the given line..
[self.view addSubview:myButton];
Button Action
- (IBAction)buttonClicked:(id)sender
{
NSLog(@"Hi!");
}
You can write the code inside the ViewDidLoad method and just test the application it must look alike the given image.
You can also create a button in Interface builder but few programmers also use the programatic approach. Both the ways are ok to me .. but i prefer Interface builder to reduce the coding part. But again it's a personal choice ..you can use any method and it'll work fine.