iOS 位枚舉

在 iOS 開發中,我們使用系統的枚舉定義的時候,經??梢钥吹?code>位枚舉:

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
};

需要掌握位枚舉,我們需要先了解位運算位移

位運算

位運算有兩種:位或(|)位與(&)

  • 位或(|) :兩個進行或(|)運算。運算規則:兩個運算的只要有一個為1則運算結果為1,否則為0

如:
0000 0001 | 0000 0010 結果為:0000 0011
0000 0000 | 0000 0000 結果為:0000 0000

  • 位與(&) :兩個進行與(&)運算。運算規則:兩個運算的都為1則運算結果為1,否則為0

如:
0000 0001 & 0000 0001 結果為:0000 0001
0000 0001 & 0000 0010 結果為:0000 0000

位移

位移包含兩種:左移(<<)右移(>>)

  • << :將一個數的二進制位向左移動 n 位,高位丟棄,低位補 0。如將數字1(0000 0001)左移兩位得到結果為:4(0000 0100)。表述為:1 << 2。

左移就是將一個數乘以 2 的 n 次方。

  • >> :將一個數的二進制位向右移動 n 位,低位丟棄,高位補 0。如將數字4(0000 0100)右移兩位得到結果為:1(0000 0001)。表述為:4 >> 2。

右移就是將一個數除以 2 的 n 次方。

iOS 位枚舉

我們有如下定義:

typedef NS_ENUM(NSUInteger, HJDirection) {
    // 0000 0001
    HJDirectionLeft = 1 << 0,
    // 0000 0010
    HJDirectionRight = 1 << 1,
    // 0000 0100
    HJDirectionTop = 1 << 2,
    // 0000 1000
    HJDirectionBottom = 1 << 3
};

PS:定義一個位枚舉時,我們通常以一個數字作為基準,如數字1,然后對該數字進行左移(右移),這樣我們才能在后面使用中判斷是否包含某個枚舉值。

使用:

//獲取所有方向(位或運算)
//0000 1111
HJDirection directionAll = HJDirectionLeft | HJDirectionRight | HJDirectionTop | HJDirectionBottom;

//獲取是否包含某個方向(位與運算)
if ((directionAll & HJDirectionLeft) == HJDirectionLeft) {
    //0000 0001
    NSLog(@"滿足條件:左方向");
}
if ((directionAll & HJDirectionRight) == HJDirectionRight) {
    //0000 0010
    NSLog(@"滿足條件:右方向");
}
if ((directionAll & HJDirectionTop) == HJDirectionTop) {
    //0000 0100
    NSLog(@"滿足條件:上方向");
}
if ((directionAll & HJDirectionBottom) == HJDirectionBottom) {
    //0000 1000
    NSLog(@"滿足條件:下方向");
}

我們回到開始的 UIControlState 枚舉定義

我們在定義 UIButton 狀態時,一般會用到 UIControlStateNormalUIControlStateHighlighted 、UIControlStateSelected,但我們怎么去定義一個選中狀態下的高亮呢?如果我們單純的使用 UIControlStateHighlighted, 我們得到的只是默認狀態下的高亮顯示。這時我們就需要用到位枚舉的神奇之處了。

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:@"點擊我" forState:UIControlStateNormal];
//定義普通狀態文字顏色
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//定義選中狀態文字顏色
[button setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
//定義普通狀態高亮文字顏色
[button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
//定義選中狀態高亮文字顏色
[button setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected | UIControlStateHighlighted];

Done !

Link:iOS 位枚舉

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容