iOS 位枚举

    xiaoxiao2022-05-26  212

    在 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 00110000 0000 | 0000 0000 结果为:0000 0000

    位与(&) :两个位进行与(&)运算。运算规则:两个运算的位都为1则运算结果为1,否则为0

    如:0000 0001 & 0000 0001 结果为:0000 00010000 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 位枚举

    相关资源:七夕情人节表白HTML源码(两款)

    最新回复(0)