UIButton 是 iOS 開發中最常用的控件之一,本文從建立、屬性設定、顯示到自訂繪圖與綁定動作,完整梳理它的用法。
有兩種常見方式。第一種是傳統的 initWithFrame:
UIButton *btn1 = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 80, 44)];
第二種是使用類別方法 buttonWithType:
UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
常見的按鈕風格包含:
typedef enum {
UIButtonTypeCustom = 0, // 自訂,無風格
UIButtonTypeRoundedRect, // 白色圓角矩形
UIButtonTypeDetailDisclosure, // 藍色披露按鈕
UIButtonTypeInfoLight, // 小圓圈資訊按鈕
UIButtonTypeInfoDark, // 深色背景用的圓圈資訊按鈕
UIButtonTypeContactAdd, // 藍色加號按鈕
} UIButtonType;
Frame 屬性。用 buttonWithType 建立後,可以透過 frame 指定位置與大小:
CGRect btn2Frame = CGRectMake(10.0, 10.0, 60.0, 44.0);
btn2.frame = btn2Frame;
標題、圖片與顏色。針對特定狀態設定按鈕的標題、圖片、文字顏色、陰影與背景:
[btn1 setTitle:@"BTN1" forState:UIControlStateNormal];
[btn2 setImage:[UIImage imageNamed:@"pic"] forState:UIControlStateNormal];
[btn1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[btn1 setTitleShadowColor:[UIColor grayColor] forState:UIControlStateNormal];
[btn1 setBackgroundImage:[UIImage imageNamed:@"PIC"] forState:UIControlStateHighlighted];
上面幾個方法都有共同的 forState 參數,它決定屬性要在何種狀態下呈現。常見的控件狀態如下:
enum {
UIControlStateNormal = 0, // 常態
UIControlStateHighlighted = 1 << 0, // 高亮
UIControlStateDisabled = 1 << 1, // 禁用
UIControlStateSelected = 1 << 2, // 選中
};
掌握前四種狀態大致就夠用了。此外還有幾個微調外觀的屬性:
btn1.adjustsImageWhenHighlighted = NO; // 高亮時不調整圖片
btn1.adjustsImageWhenDisabled = NO; // 禁用時不調整圖片
btn1.showsTouchWhenHighlighted = YES; // 按下時發光
跟其他視圖一樣,用 addSubview 把按鈕加入畫面即可:
[self.view addSubview:btn1];
[self.view addSubview:btn2];
你可以透過繼承 UIButton 來定制自己的按鈕類別,重載以下方法以指定各部位的邊界(注意:這些方法是寫給系統呼叫的,不要自己直接呼叫):
backgroundRectForBounds // 背景邊界
contentRectForBounds // 內容邊界
titleRectForContentRect // 文字標題邊界
imageRectForContentRect // 圖片邊界
例如:
- (CGRect)imageRectForContentRect:(CGRect)bounds{
return CGRectMake(0.0, 0.0, 44, 44);
}
按鈕存在的意義就是觸發動作,透過 addTarget 綁定事件與回呼方法:
[btn1 addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
-(void)btnPressed:(id)sender{
UIButton* btn = (UIButton*)sender;
// 開始寫你自己的動作
}
把以上幾個環節串起來,你就能靈活駕馭 UIButton,打造符合需求的互動按鈕了。