iOS UIButton之UIControlEvents介紹

級別:★★☆☆☆
標簽:「UIButton」「UIControlEvents」
作者: WYW
審校: QiShare團隊

大家好,今天小編帶大家研究一下UIButton里 各種UIControlEvents的具體區別。
首先,我們先看下蘋果官方對UIControlEvents的定義。

UIControlEvents 相關位移枚舉

typedef NS_OPTIONS(NSUInteger, UIControlEvents) {
        UIControlEventTouchDown                                         = 1 <<  0,      // on all touch downs
        UIControlEventTouchDownRepeat                                   = 1 <<  1,      // on multiple touchdowns (tap count > 1)
        UIControlEventTouchDragInside                                   = 1 <<  2,
        UIControlEventTouchDragOutside                                  = 1 <<  3,
        UIControlEventTouchDragEnter                                    = 1 <<  4,
        UIControlEventTouchDragExit                                     = 1 <<  5,
        UIControlEventTouchUpInside                                     = 1 <<  6,
        UIControlEventTouchUpOutside                                    = 1 <<  7,
        UIControlEventTouchCancel                                       = 1 <<  8,
        
        UIControlEventValueChanged                                      = 1 << 12,     // sliders, etc.
        UIControlEventPrimaryActionTriggered NS_ENUM_AVAILABLE_IOS(9_0) = 1 << 13,     // semantic action: for buttons, etc.
        
        UIControlEventEditingDidBegin                                   = 1 << 16,     // UITextField
        UIControlEventEditingChanged                                    = 1 << 17,
        UIControlEventEditingDidEnd                                     = 1 << 18,
        UIControlEventEditingDidEndOnExit                               = 1 << 19,     // 'return key' ending editing
        
        UIControlEventAllTouchEvents                                    = 0x00000FFF,  // for touch events
        UIControlEventAllEditingEvents                                  = 0x000F0000,  // for UITextField
        UIControlEventApplicationReserved                               = 0x0F000000,  // range available for application use
        UIControlEventSystemReserved                                    = 0xF0000000,  // range reserved for internal framework use
        UIControlEventAllEvents                                         = 0xFFFFFFFF   // 相當于上邊的所有值的 或
    };

UIControlEvents的具體解釋

  • UIControlEventTouchDown
    官方:A touch-down event in the control.
    解釋:觸下control 中的事件(這個可以用于監測 剛剛按下按鈕 或者是UISlider的時候的事件)

  • UIControlEventTouchDownRepeat
    官方:A repeated touch-down event in the control; for this event the value of the UITouch tapCount method is greater than one.
    解釋:在control上重復地按下的事件 這個事件的tap數量大于1

  • UIControlEventTouchDragInside
    官方: An event where a finger is dragged inside the bounds of the control.
    解釋:手指在control的bounds范圍內拖動的的事件

  • UIControlEventTouchDragOutside
    官方: An event where a finger is dragged just outside the bounds of the control.
    解釋:當手指拖動剛好在control的bounds 范圍外的事件

  • UIControlEventTouchDragEnter
    官方:An event where a finger is dragged into the bounds of the control.
    解釋:當手指拖動進入control范圍內的事件

  • UIControlEventTouchDragExit
    官方: An event where a finger is dragged from within a control to outside its bounds.
    解釋:當手指從control范圍內到它的bounds外的時候的事件

  • UIControlEventTouchUpInside
    官方:A touch-up event in the control where the finger is inside the bounds of the control.
    解釋:手指在在control內部 觸發的touch-up事件(經常給按鈕添加這個事件)

  • UIControlEventTouchUpOutside
    官方:A touch-up event in the control where the finger is outside the bounds of the control.
    解釋:手指在在control外部 觸發的touch-up事件

  • UIControlEventTouchCancel
    官方: A system event canceling the current touches for the control.
    解釋:一種系統事件 取消control當前觸摸的事件

  • UIControlEventValueChanged
    官方:A touch dragging or otherwise manipulating a control, causing it to emit a series of different values.
    解釋:拖動觸摸 或 其他操作一個control引起這個control顯示一系列不同的值(像UISlider在拖動的時候值的變化可以通過這個事件來監測)

  • UIControlEventPrimaryActionTriggered
    官方: A semantic action triggered by buttons.
    解釋:按鈕觸發的語義動作? 這個沒用過

  • UIControlEventEditingDidBegin
    官方:A touch initiating an editing session in a UITextField object by entering its bounds.
    解釋:當觸摸UITextField對象后 通過進入它的bounds 初始化一個編輯會話

  • UIControlEventEditingChanged
    官方:A touch making an editing change in a UITextField object.
    解釋:觸摸UITextField對象后一個編輯改變

  • UIControlEventEditingDidEnd
    官方:A touch ending an editing session in a UITextField object by leaving its bounds.
    解釋:在手指離開TextFiled對象的bounds的時候 觸摸結束的一個編輯會話

  • UIControlEventEditingDidEndOnExit
    官方:A touch ending an editing session in a UITextField object.
    解釋:在UITextField對象中 觸摸結束編輯會話

  • UIControlEventAllTouchEvents
    官方:All touch events.
    解釋:所有的觸摸事件

  • UIControlEventAllEditingEvents
    官方:All editing touches for UITextField objects.
    解釋: 對于UITextFiled對象的所有的的編輯觸摸

  • UIControlEventApplicationReserved
    官方:A range of control-event values available for application use.
    解釋: 為應用使用的預留的 一系列可用的的control-event值

  • UIControlEventSystemReserved
    官方:A range of control-event values reserved for internal framework use.
    解釋: 為內部framework預留的 一系列control-event values

  • UIControlEventAllEvents
    官方:All events, including system events.
    解釋:所有的事件 包括系統事件

Demo研究:

思路: 設計了5個按鈕 用不同方式添加事件處理(控制變量法)
  • 第一個Button:創建按鈕添加事件,并且添加事件處理,點擊按鈕后方法正常執行;
  • 第二個Button:控制 targetnil,點擊按鈕后方法正常執行,在響應鏈上找一個對象響應消息;
  • 第三個Button:控制 actionnull 或者是 方法寫錯名字 會崩潰 unrecognized selector sent to instance 0x7fef757063e0';
  • 第四個Button:給按鈕添加 事件 UIControlEventAllEvents
  • 第五個Button: 復位按鈕 當前功能是設置 kDisplaceStep = 0;

Demo通過遍歷UIControlEvents 位移枚舉,找出按鈕添加了那些方法。

編譯器Demo截圖

相關代碼

#import "QiButton_UIControlEventsViewController.h"

static NSUInteger kDisplaceStep = 0;    //!< 偏移位數
static long long const kDisplacementBase = 0x01;   //!< 偏移基數

@implementation QiButton_UIControlEventsViewController {
    
    NSDictionary *_controlEventDictionary;  //!< UIControlEvents 枚舉字典
}

- (void)viewDidLoad {

    [super viewDidLoad];
    
    self.title = @"UIControlEvents";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self prepareData];
    
    [self controlEventsDemo];
}

#pragma mark - private functions

- (void)prepareData {
    
    _controlEventDictionary = @{
                              @(UIControlEventTouchDown) : @"UIControlEventTouchDown",
                              @(UIControlEventTouchDownRepeat) : @"UIControlEventTouchDownRepeat",
                              @(UIControlEventTouchDragInside) : @"UIControlEventTouchDragInside",
                              @(UIControlEventTouchDragOutside) : @"UIControlEventTouchDragOutside",
                              @(UIControlEventTouchDragEnter) : @"UIControlEventTouchDragEnter",
                              @(UIControlEventTouchDragExit) : @"UIControlEventTouchDragExit",
                              @(UIControlEventTouchUpInside) : @"UIControlEventTouchUpInside",
                              @(UIControlEventTouchUpOutside) : @"UIControlEventTouchUpOutside",
                              @(UIControlEventTouchCancel) : @"UIControlEventTouchCancel",
                              @(UIControlEventValueChanged) : @"UIControlEventValueChanged",
                              @(UIControlEventPrimaryActionTriggered) : @"UIControlEventPrimaryActionTriggered",
                              @(UIControlEventEditingDidBegin):@"UIControlEventEditingDidBegin",
                              @(UIControlEventEditingChanged) : @"UIControlEventEditingChanged",
                              @(UIControlEventEditingDidEnd):@"UIControlEventEditingDidEnd",
                              @(UIControlEventEditingDidEndOnExit):@"UIControlEventEditingDidEndOnExit",
                              @(UIControlEventAllTouchEvents):@"UIControlEventAllTouchEvents",
                              @(UIControlEventAllEditingEvents):@"UIControlEventAllEditingEvents",
                              @(UIControlEventApplicationReserved):@"UIControlEventApplicationReserved",
                              @(UIControlEventSystemReserved):@"UIControlEventSystemReserved",
                              @(UIControlEventAllEvents):@"UIControlEventAllEvents",
                              };
}

- (void)controlEventsDemo {
    
    // - (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
    /**
     * Demo思路 創建5個按鈕 并且添加事件處理
        * 1. 中規中矩創建按鈕添加事件 并且添加事件處理 點擊按鈕后 方法正常執行
        * 2. target 設置為nil 點擊按鈕后方法正常執行 在響應鏈上找一個對象響應消息
        * 3. action 設置為null 或者是 方法寫錯名字 會崩潰 unrecognized selector sent to instance 0x7fef757063e0'
        * 4. 給按鈕添加 事件 UIControlEventAllEvents
        * 5. 復位按鈕 當前功能是設置 kDisplaceStep = 0;
        查看效果:
        * 6. 讀者可以試著改變UIControlEvents 位移枚舉 輸出為按鈕添加的UIControlEvents的內容
        * 其中還有別的內容像 UITextField 像 UISlider 中的一些事件處理
     */
    self.edgesForExtendedLayout = UIRectEdgeNone;
    CGFloat screenH = [UIScreen mainScreen].bounds.size.height;
    CGFloat screenW = [UIScreen mainScreen].bounds.size.width;
    if (screenH == 812.0 && screenW == 375.0) {
        screenH -= 122.0;
    }else {
        screenH -= 64.0;
    }
    CGFloat btnTopMargin = 20.0;
    CGFloat btnW = [UIScreen mainScreen].bounds.size.width;
    CGFloat btnH = (screenH - (btnTopMargin * 5)) / 5;
    
    UIButton *normalBtn = [[UIButton alloc] initWithFrame:CGRectMake(.0, btnTopMargin, btnW, btnH)];
    [self.view addSubview:normalBtn];
    [normalBtn setTitle:@"normalButton" forState:UIControlStateNormal];
    normalBtn.backgroundColor = [UIColor lightGrayColor];
    [normalBtn addTarget:self action:@selector(normalButtonClicked:) forControlEvents:UIControlEventTouchDown];
    [normalBtn addTarget:self action:@selector(normalButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *targetNilBtn = [[UIButton alloc] initWithFrame:CGRectMake(.0, (btnTopMargin * 2 + btnH), btnW, btnH)];
    [self.view addSubview:targetNilBtn];
    [targetNilBtn setTitle:@"targetNilButton" forState:UIControlStateNormal];
    targetNilBtn.backgroundColor = [UIColor grayColor];
    [targetNilBtn addTarget:nil action:@selector(targetNilButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [targetNilBtn addTarget:nil action:@selector(targetNilButtonClicked:) forControlEvents:UIControlEventTouchDown];
    
    UIButton *selectorNullBtn = [[UIButton alloc] initWithFrame:CGRectMake(.0, (btnTopMargin * 3 + btnH * 2), btnW, btnH)];
    [self.view addSubview:selectorNullBtn];
    [selectorNullBtn setTitle:@"null Selector Button" forState:UIControlStateNormal];
    selectorNullBtn.backgroundColor = [UIColor darkGrayColor];
    [selectorNullBtn addTarget:self action:@selector(null) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *allEventsBtn = [[UIButton alloc] initWithFrame:CGRectMake(.0, (btnTopMargin * 4 + btnH * 3), btnW, btnH)];
    [self.view addSubview:allEventsBtn];
    [allEventsBtn setTitle:@"allEventsButton" forState:UIControlStateNormal];
    allEventsBtn.backgroundColor = [[UIColor darkTextColor] colorWithAlphaComponent:0.6];
    [allEventsBtn addTarget:self action:@selector(allEventButtonClicked:) forControlEvents:UIControlEventAllEvents];
    
    UIButton *resetBtn = [[UIButton alloc] initWithFrame:CGRectMake(.0, (btnTopMargin * 5 + btnH * 4), btnW, btnH)];
    [self.view addSubview:resetBtn];
    [resetBtn setTitle:@"復位" forState:UIControlStateNormal];
    resetBtn.backgroundColor = [[UIColor darkTextColor] colorWithAlphaComponent:0.8];
    [resetBtn addTarget:self action:@selector(resetButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
}


#pragma mark - action functions

- (void)normalButtonClicked:(UIButton *)sender {
    
    UIControlEvents tempEvents = sender.allControlEvents;
    
    for (; kDisplaceStep < 32; ++ kDisplaceStep) {
        if (tempEvents & (kDisplacementBase << kDisplaceStep)) {
            NSLog(@"添加的allControlEvents:%lu",(unsigned long)sender.allControlEvents);
            NSLog(@"分別為: %llu--%@", (kDisplacementBase << kDisplaceStep),_controlEventDictionary[@(kDisplacementBase << kDisplaceStep)]); // %o %x
            // 65 相當于 UIControlEventTouchDown | UIControlEventTouchUpInside
        }
    }
    NSLog(@"%s",__FUNCTION__);
}

- (void)targetNilButtonClicked:(UIButton *)sender {
    
    NSLog(@"添加的allControlEvents:%lu",(unsigned long)sender.allControlEvents);
    NSLog(@"%s",__FUNCTION__);
    // 調用次數為2 是因為測試的UIControlEventTouchDown 和 UIControlEventTouchUpInside 各調用了一次
}

- (void)allEventButtonClicked:(UIButton *)sender {
    
    UIControlEvents tempEvents = sender.allControlEvents;
    for (; kDisplaceStep < 32; ++ kDisplaceStep) {
        if (tempEvents & (kDisplacementBase << kDisplaceStep)) {
            NSLog(@"添加的allControlEvents:%lu",(unsigned long)sender.allControlEvents);
            NSLog(@"可能有: %llu--%@", (kDisplacementBase << kDisplaceStep),_controlEventDictionary[@(kDisplacementBase << kDisplaceStep)]); // %o %x
        }
    }
    // 其輸出結果代表其可以響應很多事件,這種情況下就不能夠準確的確定是那個事件了, 因為可能是彼此之間二進制位重復的值 做的 或 操作后的結果。
    NSLog(@"%s",__FUNCTION__);
}

- (void)resetButtonClicked:(UIButton *)sender {
    
    NSLog(@"%s",__FUNCTION__);
    kDisplaceStep = 0;
}

@end

代碼GitHub地址

特別致謝:

蘋果關于UIControlEvents的官方文檔


最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,702評論 6 534
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,615評論 3 419
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,606評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,044評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,826評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,227評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,307評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,447評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,992評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,807評論 3 355
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,001評論 1 370
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,550評論 5 361
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,243評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,667評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,930評論 1 287
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,709評論 3 393
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,996評論 2 374