下面我們先來看看我們在開發(fā)中經(jīng)常使用的蘋果為我們提供的兩個枚舉值:
NS_ENUM
typedef NS_ENUM(NSInteger, UIButtonType) {
UIButtonTypeCustom = 0, // no button type
UIButtonTypeSystem NS_ENUM_AVAILABLE_IOS(7_0), // standard system button
UIButtonTypeDetailDisclosure,
UIButtonTypeInfoLight,
UIButtonTypeInfoDark,
UIButtonTypeContactAdd,
UIButtonTypePlain API_AVAILABLE(tvos(11.0)) API_UNAVAILABLE(ios, watchos), // standard system button without the blurred background view
UIButtonTypeRoundedRect = UIButtonTypeSystem // Deprecated, use UIButtonTypeSystem instead
};
該類型的枚舉我們只能傳遞一個值,不能組合使用,比如:
UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
關(guān)于這種枚舉沒有什么多說的,今天我們重點討論的是下面的這種枚舉以及實現(xiàn)方式
NS_OPTIONS
typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {
UIViewAutoresizingNone = 0,
UIViewAutoresizingFlexibleLeftMargin = 1 << 0,
UIViewAutoresizingFlexibleWidth = 1 << 1,
UIViewAutoresizingFlexibleRightMargin = 1 << 2,
UIViewAutoresizingFlexibleTopMargin = 1 << 3,
UIViewAutoresizingFlexibleHeight = 1 << 4,
UIViewAutoresizingFlexibleBottomMargin = 1 << 5
};
這種枚舉與上面的不同,在使用的時候我們可以組合使用,傳遞多個值 比如:
self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleTopMargin;
那么不知道讀者有沒有想過這樣一個問題,我們傳遞了多個數(shù)據(jù),那么程序內(nèi)部是如何去判斷我們分別傳遞了那些值呢?
再具體的分析之前我們先來回憶一下 位運算的相關(guān)知識
|
如果兩個相應(yīng)的二進制位只要有一個是1低散,結(jié)果就是1;否則為0骡楼。
比如
00000001
| 00000010
____________
00000011
&
如果兩個相應(yīng)的二進制位都為1熔号,則該位的結(jié)果值為1;否則為0鸟整。
比如
00000011 00000011 00000011
& 00000001 & 00000010 &上一個之前不包含的數(shù)據(jù)=> & 00000100
____________ ______________ ______________
00000001 00000010 00000000
通過上面的運算我們可以看到 通過 &
運算之后可以得到它本身.
也就是如果e = a| b | c | d引镊,那么e & a 、e & b 篮条、e & c 祠乃、 e & d都為true.
就是說你這個枚舉值包含了那些原始枚舉值,&操作值都為true.否則為false
<<
向左移一位兑燥,右邊自動補0
比如 1 << 1 = 2
00000001 << 1
00000010 = 2
所以通過上面的分析我們不難猜出位移枚舉的內(nèi)部判斷邏輯應(yīng)該是這樣的:
- (void)setOptions:(UIViewAutoresizing)options
{
if (options & UIViewAutoresizingFlexibleWidth) {
NSLog(@"包含了UIViewAutoresizingFlexibleWidth");
}
if (options & UIViewAutoresizingFlexibleHeight) {
NSLog(@"包含了UIViewAutoresizingFlexibleWidth");
}
if (options & UIViewAutoresizingFlexibleTopMargin) {
NSLog(@"包含了UIViewAutoresizingFlexibleWidth");
}
}