UIButton
UIButton相關常用方法和屬性
能夠定義的button類型有以下6種:
typedef NS_ENUM(NSInteger, UIButtonType) {
UIButtonTypeCustom 自定義風格
UIButtonTypeDetailDisclosure 藍色小箭頭按鈕
UIButtonTypeInfoLight 亮色感嘆號
UIButtonTypeInfoDark 暗色感嘆號
UIButtonTypeContactAdd 十字加號按鈕
UIButtonTypeRoundedRect 圓角矩形 (= UIButtonTypeSystem)
}
創建一個普通顯示文字的按鈕
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
創建一個顯示圖片的按鈕
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(100, 200, 100, 100);
//設置不同狀態下的圖片
[button setImage:[UIImage imageNamed:@"Off"] forState:UIControlStateNormal];
//高亮
[button setImage:[UIImage imageNamed:@"On"] forState:UIControlStateHighlighted];
//選中狀態
[button setImage:[UIImage imageNamed:@"On"] forState:UIControlStateSelected];
設置位置
button.frame = CGRectMake(100, 100, 80, 40);
設置不同狀態下的文字
UIControlStateNormal 正常狀態
UIControlStateHighlighted 高亮狀態
UIControlStateSelected 選中狀態
UIControlStateDisabled 不可用狀態
[button setTitle:@"正常狀態" forState:UIControlStateNormal];
[button setTitle:@"高亮狀態" forState:UIControlStateHighlighted];
[button setTitle:@"選中狀態" forState:UIControlStateSelected];
設置按鈕不同狀態下的顏色
[button setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor yellowColor] forState:UIControlStateHighlighted];
統一設置所有顏色(優先級比較低)
[button setTintColor:[UIColor blueColor]];
設置背景顏色
button.backgroundColor = [UIColor redColor];
設置字體大小
button.titleLabel.font = [UIFont systemFontOfSize:20];
添加響應事件
[button addTarget:<#(nullable id)#>
action:<#(nonnull SEL)#>
forControlEvents:<#(UIControlEvents)#>];
addTarget:誰來實現這個函數,實現者對象就是"誰",一般是self
action:@selector(selector) 函數對象,當按鈕滿足p3事件類型的時候調用
forControlEvents:<#(UIControlEvents)#> 事件處理類型函數
[button addTarget:self action:@selector(pressAction:) forControlEvents:UIControlEventTouchUpInside];
響應事件的枚舉值的詳解
typedef NS_OPTIONS(NSUInteger, UIControlEvents) :
UIControlEventTouchDown
單點觸摸按下事件:用戶點觸屏幕,或者又有新手指落下的時候。
UIControlEventTouchDownRepeat
多點觸摸按下事件,點觸計數大於1:用戶按下第二、三、或第四根手指的時候。
UIControlEventTouchDragInside
當一次觸摸在控件窗口內拖動時。
UIControlEventTouchDragOutside
當一次觸摸在控件窗口之外拖動時。
UIControlEventTouchDragEnter
當一次觸摸從控件窗口之外拖動到內部時。
UIControlEventTouchDragExit
當一次觸摸從控件窗口內部拖動到外部時。
UIControlEventTouchUpInside
所有在控件之內觸摸擡起事件。
UIControlEventTouchUpOutside
所有在控件之外觸摸擡起事件(點觸必須開始與控件內部纔會發送通知)。
UIControlEventTouchCancel
所有觸摸取消事件,即一次觸摸因爲放上了太多手指而被取消,或者被上鎖或者電話呼叫打斷。
UIControlEventTouchChanged
當控件的值發生改變時,發送通知。用於滑塊、分段控件、以及其他取值的控件。你可以配置滑塊控件何時發送通知,在滑塊被放下時發送,或者在被拖動時發送。
UIControlEventEditingDidBegin
當文本控件中開始編輯時發送通知。
UIControlEventEditingChanged
當文本控件中的文本被改變時發送通知。
UIControlEventEditingDidEnd
當文本控件中編輯結束時發送通知。
UIControlEventEditingDidOnExit
當文本控件內通過按下回車鍵(或等價行爲)結束編輯時,發送通知。
UIControlEventAlltouchEvents
通知所有觸摸事件。
UIControlEventAllEditingEvents
通知所有關於文本編輯的事件。
UIControlEventAllEvents
通知所有事件。