typedef NS_ENUM(NSInteger, UIButtonType) {
UIButtonTypeCustom = 0, // 自定義,無按鈕類型
UIButtonTypeSystem, // 系統標準按鈕
UIButtonTypeDetailDisclosure, // 詳細說明箭頭
UIButtonTypeInfoLight, // 亮色資訊鈕
UIButtonTypeInfoDark, // 暗色資訊鈕
UIButtonTypeContactAdd, // 添加聯絡人
UIButtonTypeRoundedRect = UIButtonTypeSystem, // 已棄用,改用 UIButtonTypeSystem
};
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.tag = 100; // 給 Button 添加標記,方便在不同方法中取得同一控件
button.frame = CGRectMake(30, 170, 200, 40);
[self.window addSubview:button];
// 設置按鈕文字,需指定狀態
[button setTitle:@"按鈕" forState:UIControlStateNormal];
// [button setTitle:@"Hello" forState:UIControlStateHighlighted];
[button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
// 高亮時觸發
button.showsTouchWhenHighlighted = YES;
// 為 button 綁定事件
[button addTarget:self // 接收消息的對象
action:@selector(buttonAction:) // 觸發時發送的消息
forControlEvents:UIControlEventTouchUpInside]; // 觸發方式
- (void)buttonAction {
NSLog(@"咔");
// 透過 tag 從父視圖中取得 button
UIButton *btn = (UIButton *)[self.window viewWithTag:100];
[btn setTitle:@"點我" forState:UIControlStateNormal];
// 讓 Button 失效(移除事件)
[btn removeTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
}
- (void)buttonAction:(UIButton *)sender {
sender.backgroundColor = [UIColor redColor];
}
透過 tag 標記控件、addTarget:action:forControlEvents: 綁定事件,以及 removeTarget:action:forControlEvents: 移除事件,就構成了 UIButton 最基礎也最常用的操作模式。