初始化
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0,0,100,44);
[self.view addSubview:btn];
typedef NS_ENUM(NSInteger, UIButtonType) {
UIButtonTypeCustom = 0, // no button type 自定義風格
UIButtonTypeSystem NS_ENUM_AVAILABLE_IOS(7_0), // standard system button
UIButtonTypeDetailDisclosure,//藍色小箭頭按鈕,主要做詳細說明
UIButtonTypeInfoLight,//亮色感嘆號
UIButtonTypeInfoDark,//暗色感嘆號
UIButtonTypeContactAdd,//十字加號按鈕
UIButtonTypePlain API_AVAILABLE(tvos(11.0)) API_UNAVAILABLE(ios, watchos), // standard system button without the blurred background view
UIButtonTypeRoundedRect = UIButtonTypeSystem // Deprecated, use UIButtonTypeSystem instead 圓角矩形
};
常用方法和屬性
屬性和方法 | 解釋 |
---|---|
contentEdgeInsets | 內容內距離 |
titleEdgeInsets | 標題內距離 |
reversesTitleShadowWhenHighlighted; | 標題的陰影改變時,按鈕是否高亮顯示。默認爲NO |
imageEdgeInsets; | 圖片內邊距 |
adjustsImageWhenHighlighted | 按鈕高亮的情況下,圖像的顏色是否要加深一點。默認是YES |
adjustsImageWhenDisabled | 按鈕禁用的情況下,圖像的顏色是否要加深一點。默認是YES |
showsTouchWhenHighlighted | 按下按鈕是否會發光 默認是NO |
buttonType | button的類型 |
currentTitle | 獲取按鈕當前標題 |
currentTitleColor | 獲取按鈕當前標題顏色 |
currentTitleShadowColor | 獲取按鈕當前陰影標題顏色 |
currentImage | 獲取按鈕當前按鈕內圖像 |
currentBackgroundImage | 獲取按鈕當前標題背景圖片 |
currentAttributedTitle | 獲取按鈕當前標題富文本 |
- (CGRect)backgroundRectForBounds:(CGRect)bounds | 指定背景邊界 |
- (CGRect)contentRectForBounds:(CGRect)bounds | 指定內容邊界 |
- (CGRect)titleRectForContentRect:(CGRect)contentRect | 指定標題邊界 |
- (CGRect)imageRectForContentRect:(CGRect)contentRect | 指定圖片邊界 |
並不可以通過設置titleLabel屬性的文本來設置按鈕標題。在蘋果官方文檔中有描述
[btn setTitle:@"按鈕" forState:UIControlStateNormal];//設置標題
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];//設置文字顏色
btn.titleLabel.font=[UIFont systemFontOfSize:18];//設置標題字體的大小
[btn setBackgroundColor:[UIColor orangeColor]];//設置背景顏色
[btn setBackgroundImage:[UIImage imageNamed:@"bg.png"] forState:UIControlStateNormal];//設置button的背景圖片
[btn setImage:image forState:UIControlStateNormal];//設置前景圖片 前景圖片必須是鏤空圖,或者是線條勾勒的圖片
[btn setTitleShadowColor:[UIColor purpleColor] forState:UIControlStateNormal];//設置陰影顏色
[btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];//添加按鈕事件
btn.enabled=YES;//按鈕是否可用
btn.select = YES;//按鈕是否選中
btn.showsTouchWhenHighlighted = YES;//設置點擊時是否高亮
UIControlState
typedef NS_OPTIONS(NSUInteger, UIControlState) {
UIControlStateNormal = 0, //控件的正常或默認狀態 ,即已啓用但未選中也未突出顯示
UIControlStateHighlighted = 1 << 0, // used when UIControl isHighlighted is set 突出顯示控件的狀態 俗稱高亮
UIControlStateDisabled = 1 << 1, //禁用控件狀態
UIControlStateSelected = 1 << 2, // flag usable by app (see below)選擇控件的狀態
UIControlStateFocused NS_ENUM_AVAILABLE_IOS(9_0) = 1 << 3, // Applicable only when the screen supports focus獲得焦點狀態
UIControlStateApplication = 0x00FF0000, // additional flags available for application use附加的控制狀態標誌可供應用程序使用
UIControlStateReserved = 0xFF000000 // flags reserved for internal framework use內部框架使用保留的控制狀態
};