在 iOS 開發(fā)中,我們使用系統(tǒng)的枚舉定義的時候,經(jīng)??梢钥吹?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
};
需要掌握位枚舉,我們需要先了解位運算 和 位移:
位運算
位運算有兩種:位或(|) 和 位與(&)
-
位或(|):兩個位進行或(|)運算。運算規(guī)則:兩個運算的位只要有一個為1則運算結(jié)果為1,否則為0
如:
0000 0001 | 0000 0010 結(jié)果為:0000 0011
0000 0000 | 0000 0000 結(jié)果為:0000 0000
-
位與(&):兩個位進行與(&)運算。運算規(guī)則:兩個運算的位都為1則運算結(jié)果為1,否則為0
如:
0000 0001 & 0000 0001 結(jié)果為:0000 0001
0000 0001 & 0000 0010 結(jié)果為:0000 0000
位移
位移包含兩種:左移(<<) 和 右移(>>)
-
<<:將一個數(shù)的二進制位向左移動 n 位,高位丟棄,低位補0。如將數(shù)字1(0000 0001)左移兩位得到結(jié)果為:4(0000 0100)。表述為:1 << 2。
左移就是將一個數(shù)乘以 2 的 n 次方。
-
>>:將一個數(shù)的二進制位向右移動 n 位,低位丟棄,高位補0。如將數(shù)字4(0000 0100)右移兩位得到結(jié)果為:1(0000 0001)。表述為:4 >> 2。
右移就是將一個數(shù)除以 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:定義一個位枚舉時,我們通常以一個數(shù)字作為基準(zhǔn),如數(shù)字
1,然后對該數(shù)字進行左移(右移),這樣我們才能在后面使用中判斷是否包含某個枚舉值。
使用:
//獲取所有方向(位或運算)
//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 狀態(tài)時,一般會用到 UIControlStateNormal 、UIControlStateHighlighted 、UIControlStateSelected,但我們怎么去定義一個選中狀態(tài)下的高亮呢?如果我們單純的使用 UIControlStateHighlighted, 我們得到的只是默認狀態(tài)下的高亮顯示。這時我們就需要用到位枚舉的神奇之處了。
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:@"點擊我" forState:UIControlStateNormal];
//定義普通狀態(tài)文字顏色
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//定義選中狀態(tài)文字顏色
[button setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
//定義普通狀態(tài)高亮文字顏色
[button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
//定義選中狀態(tài)高亮文字顏色
[button setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected | UIControlStateHighlighted];
Done !
Link:iOS 位枚舉