IPad development: Add button dynamically

Source: Internet
Author: User

I am new to iPad development. I need to write down what I recently used so that I can forget to find it again later.

You can click an existing button to automatically create a new button and add an event to the new button. A prompt box is displayed.

1. Run Xcode 4.2 and create a Single View Application project named DynamicButton:

2. Open ViewController. xib, drag a button to the view, and set the button name to "add a button ".

3. Select this button, press Ctrl, and drag the button to the specified position of ViewController. h file:

Release the mouse and enter the following information in the pop-up window:

Add the RESPONSE event addButton for this button.

4. Open ViewController. m, find the addButton function, and add the following code:

 
 
 
01
-(IBAction) addButton :( id) sender {
02
// Add a button dynamically
03
CGRect frame = CGRectMake (300,300,300, 50 );
04
UIButton * button = [UIButton buttonWithType: UIButtonTypeRoundedRect];
05
Button. frame = frame;
06
[Button setTitle: @ "newly added dynamic button" forState: UIControlStateNormal];
07
Button. backgroundColor = [UIColor clearColor];
08
Buttons. tag = 2000;
09
[Button addTarget: self action: @ selector (buttonClicked :) forControlEvents: UIControlEventTouchUpInside];
10
[Self. view addSubview: button];
11
}
 
 
5. Add a function after the addButton function:
 
 
 
 
01
// This is the response function of the new button.
02
-(IBAction) buttonClicked :( id) sender {
03
UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @ "prompt"
04
Message: @ "click the Dynamic Button! "
05
Delegate: self
06
CancelButtonTitle: @ "OK"
07
OtherButtonTitles: nil];
08
[Alert show];
09
[Alert release];
10
} 6. Compile and run:

 



From the Gemini blog

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.