UIButton 就是一個按鈕控件。當我們用手指點擊它時,會產生對應的事件,點擊的瞬間或許還會伴隨顏色變化。它既可以顯示文字,也可以顯示圖片,還能動態調整內部的圖片與文字,甚至支援屬性化字符串(這個概念後面會再詳談)。
下面透過程式碼完整說明 UIButton 的屬性與方法:
- (void)viewDidLoad {
[super viewDidLoad];
/*
typedef NS_ENUM(NSInteger, UIButtonType) {
UIButtonTypeCustom = 0, // 自定義風格
UIButtonTypeSystem, // 系統標準按鈕
UIButtonTypeDetailDisclosure, // 藍色小箭頭,常用於詳細說明
UIButtonTypeInfoLight, // 亮色感嘆號
UIButtonTypeInfoDark, // 暗色感嘆號
UIButtonTypeContactAdd, // 加號按鈕
UIButtonTypeRoundedRect = UIButtonTypeSystem, // 系統預設圓角矩形
};
*/
// 建立一個圓角矩形類型的按鈕(系統預設)
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
// 設定 frame:坐標 (20, 20),寬高 (100, 100)
btn.frame = CGRectMake(20, 20, 100, 100);
// 設定背景顏色與渲染顏色
btn.backgroundColor = [UIColor greenColor];
btn.tintColor = [UIColor blackColor];
// 設定按鈕的填充圖片:正常狀態
[btn setImage:[UIImage imageNamed:@"2.png"] forState:UIControlStateNormal];
// 設定按鈕的填充圖片:高亮(被點擊)狀態
[btn setImage:[UIImage imageNamed:@"1.png"] forState:UIControlStateHighlighted];
// 設定按鈕上顯示的文字與文字顏色
[btn setTitle:@"" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[btn setTitleShadowColor:[UIColor blueColor] forState:UIControlStateNormal];
// 設定背景圖片
[btn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
// 設定屬性字符串
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"設置屬性字符串"];
[btn setAttributedTitle:attrString forState:UIControlStateNormal];
// 預設高亮時圖片顏色會變深,設為 NO 可取消此效果
btn.adjustsImageWhenHighlighted = NO;
// 預設禁用時圖片顏色會變深,設為 NO 可取消此效果
btn.adjustsImageWhenDisabled = NO;
// 設為 YES 時,按下按鈕會發光
btn.showsTouchWhenHighlighted = YES;
// 為按鈕增加點擊事件
[btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
// 為按鈕增加長按事件
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(btnLong:)];
longPress.minimumPressDuration = 1; // 按壓多久觸發長按
[btn addGestureRecognizer:longPress];
// 把按鈕添加到控制器的視圖上(這一步千萬別忘記)
[self.view addSubview:btn];
}
- (void)btnClick {
NSLog(@"%s", __func__);
}
- (void)btnLong:(UILongPressGestureRecognizer *)gestureRecognizer {
if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
NSLog(@"長按事件");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"消息" message:@"確定刪除嗎?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"刪除", nil];
[alert show];
}
}
UIControlEventTouchDown:單點觸摸按下;UIControlEventTouchDownRepeat:多點觸摸按下;UIControlEventTouchDragInside/Outside:在控件內外拖動;UIControlEventTouchDragEnter/Exit:從外部拖入或從內部拖出;UIControlEventTouchUpInside/Outside:在控件內外抬起;UIControlEventTouchCancel:觸摸被取消;此外還有針對文本編輯的 UIControlEventEditingDidBegin、UIControlEventEditingChanged、UIControlEventEditingDidEnd 等事件。透過 addTarget:action:forControlEvents: 就能為按鈕綁定這些事件。