iOS開發動態添加按鈕
新接觸iPad開發,把最近用到的記下來,省得以后忘記又要找。
想要的效果是,單擊一個已有的按鈕后自動創建一個新的按鈕,并為新按鈕添加事件,使得單擊時彈出提示框。
1、運行Xcode 4.2,新建一個Single View Application工程,取名DynamicButton:
2、打開ViewController.xib,拖一個按鈕到視圖,按鈕名設置為“添加一個按鈕”。
3、選中這個按鈕,按住Ctrl,把按鈕拖到ViewController.h文件指定位置:
松開鼠標,在彈出的窗口鍵入以下信息:
即為這個按鈕添加響應事件 addButton
4、打開ViewController.m,找到addButton函數,添加以下代碼:
- - (IBAction)addButton:(id)sender {
- //動態添加一個按鈕
- CGRect frame = CGRectMake(300, 300, 300, 50);
- UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
- button.frame = frame;
- [button setTitle:@"新添加的動態按鈕" forState: UIControlStateNormal];
- button.backgroundColor = [UIColor clearColor];
- button.tag = 2000;
- [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
- [self.view addSubview:button];
- }
5、在addButton函數后邊添加一個函數:
- //這個是新按鈕的響應函數
- -(IBAction) buttonClicked:(id)sender {
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
- message:@"單擊了動態按鈕!"
- delegate:self
- cancelButtonTitle:@"確定"
- otherButtonTitles:nil];
- [alert show];
- [alert release];
- }
6、編譯并運行: