UIButton 是 iOS 開發中最高頻使用的控制元件之一,但它的屬性相當零碎。下面把常用的設定一次整理出來,包含按鈕型別、標題、顏色、背景圖、陰影、對齊方式以及事件綁定。
// 建立自訂型別的按鈕(無任何預設樣式)
// UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
// 建立圓角系統樣式按鈕
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
// 位置與尺寸
button1.frame = CGRectMake(80, 250, 250, 30);
// 一般狀態的標題文字
[button1 setTitle:@"Button1" forState:UIControlStateNormal];
// 高亮(手指按下)狀態的標題文字
[button1 setTitle:@"高亮狀態" forState:UIControlStateHighlighted];
// 按下時顯示高亮光暈
[button1 setShowsTouchWhenHighlighted:YES];
// 標題顏色(同樣需要指定狀態)
[button1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
// 標題字級與字型
[button1.titleLabel setFont:[UIFont boldSystemFontOfSize:20]];
// 背景純色
[button1 setBackgroundColor:[UIColor blueColor]];
// 背景圖片:會被拉伸填滿整個按鈕
[button1 setBackgroundImage:[UIImage imageNamed:@"1.jpg"] forState:UIControlStateNormal];
// 若希望圖片保持原始尺寸,改用 setImage:forState:
// [button1 setImage:[UIImage imageNamed:@"1.jpg"] forState:UIControlStateNormal];
// 標題陰影顏色與偏移量,可做出立體感
[[button1 titleLabel] setShadowColor:[UIColor blackColor]];
[[button1 titleLabel] setShadowOffset:CGSizeMake(-0.5, -0.5)];
// 內容水平對齊方式:靠左
button1.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
// 加入畫面
[self.view addSubview:button1];
// 綁定點擊事件
[button1 addTarget:self action:@selector(Click_Button) forControlEvents:UIControlEventTouchUpInside];
}
- (void)Click_Button
{
NSLog(@"已點擊...");
}
setBackgroundImage 與 setImage 的差別:前者會把圖片拉伸填滿按鈕邊界,適合純色塊或漸層底圖;後者保留圖片原始尺寸,適合圖示(icon)。
所有跟狀態有關的 API 都要帶 forState:像是 setTitle、setTitleColor、setImage,漏掉狀態參數的話設定不會生效。
contentHorizontalAlignment:除了靠左,還有 Center、Right、Fill 等選項,決定 titleLabel 與 imageView 這一整組內容在按鈕內部的對齊方式。
未完,後續會持續補充。