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