iOS 位枚舉
在 iOS 開發中,我們使用係統的枚舉定義的時候,經常可以看到位枚舉
:
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
狀態時,一般會用到 UIControlStateNormal
、UIControlStateHighlighted
、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 位枚舉
最後更新:2017-08-25 18:32:14