1. 在ButtonTestViewController.m加入下面程式碼
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self setButtonInterface]; // 動態產生一個的Button
}
- (IBAction)onHelloActionButton:(id)sender { //當動態的Button按下時的動作
UILabel *_actionLabel = [UILabel new]; //產生一個動態的Label
_actionLabel.frame = CGRectMake(0, 0, 100, 100); //大小
_actionLabel.center = self.view.center; //位置在view的正中間
_actionLabel.backgroundColor = [UIColor blueColor]; //底色為藍色
_actionLabel.textAlignment = UITextAlignmentCenter; // 文字放置方法為對齊
_actionLabel.text = @"Hello Action";//動態Label文字展示為Hello Action
helloLabel.text = @"Hello Two"; // 同時改變 靜態Label的展示方法
[self.view addSubview:_actionLabel]; //將動態的Label放到View上展示
}
- (void)setButtonInterface // 動態產生一個的Button
{
UIButton *_helloActionButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//動態產生一個RoundedRect 形式的 Button
_helloActionButton.frame = CGRectMake(0,0, 100, 30); // 大小
//_helloActionButton.center = self.view.center;
[_helloActionButton setCenter:CGPointMake(150, 50)];//位置放在x=150, y=50的位置
[_helloActionButton addTarget:self action:@selector(onHelloActionButton:) forControlEvents:UIControlEventTouchUpInside];
//設定Button動作呼叫的function在 onHelloActionButton,方式為按下
//_helloActionButton.= @"Action Button";
[_helloActionButton setTitle:@"Action Button" forState:UIControlStateNormal];
//將動態Button上放置Action Button這兩個字
[self.view addSubview:_helloActionButton];
//將動態Button放到View上展出
}
動態Button State說明
UIControlStateNormal: 控制項為正常狀態.(有作用, 但目前沒有被使用)
UIControlStateHighlighted: 控制項正在被點選或使用中.
UIControlStateDisabled: 控制項 沒有啓用或不能使用.
UIControlStateSelected: 控制項目前被選取.
2. 結果展示如下
執行後產生動態Button按下動態Button後的結果

