iOS-Android-私房菜IOS 硬件交互

位运算在iOS中的使用

2016-03-05  本文已影响2538人  一只长毛猫

本文主要讲解三个运算符 左移(<<)、与(&)、或(|)  在iOS代码中如何使用。


我们经常能看到下面这样的代码

UIView*view = [[UIViewalloc]init];

view.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;

[self.viewaddSubview:view];

意思是,自动调整自己的宽度,保证与superView左边和右边的距离不变。自动调整自己的高度,保证与superView顶部和底部的距离不变。查看autoresizingMask的类型,其实是NSUInteger 如下

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

};

那么一个NSUInteger的类型,是怎样告诉View,既要调整自己的宽度,又要调整自己的高度的呢?


左移运算符 <<    

公式 x << 3 就是把x的各二进位左移3位

1<<1  实际就是  0001 << 1  = 0010   转成十进制后就是  2

1<<4  实际就是  0001 << 4  = 10000  转成十进制后就是  16

UIViewAutoresizingFlexibleWidth   =  00010

UIViewAutoresizingFlexibleHeight = 10000


或运算符 |

只要对应的二个二进位有一个为1时,结果位就为1

00010 | 10000  = 10010

UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight 就是

00010 | 10000 = 10010


autoresizingMask 的结果就是二进制数 10010,我们如何知道 是哪个选项被选中了?

与运算符 &

只有对应的二个二进位都为1时,结果位才是1

10010 & 00010 = 00010

判断选项是否被选中的方法如下

if(view.autoresizingMask&UIViewAutoresizingFlexibleWidth){

 NSLog(@"UIViewAutoresizingFlexibleWidth被选中了"); //code1

}

autoresizingMask = 10010

UIViewAutoresizingFlexibleWidth  = 00010

10010 & 00010 = 00010 等价于十进制 2,为真,所以code1被执行。

if(view.autoresizingMask&UIViewAutoresizingFlexibleHeight){

NSLog(@"UIViewAutoresizingFlexibleHeight被选中了");//code2

}

autoresizingMask = 10010

UIViewAutoresizingFlexibleWidth  = 10000

10010 & 10000 = 10000 等价于十进制 16,为真,所以code2被执行。

if(view.autoresizingMask&UIViewAutoresizingFlexibleLeftMargin){

NSLog(@"UIViewAutoresizingFlexibleLeftMargin");//code3

}

autoresizingMask = 10010

UIViewAutoresizingFlexibleWidth  = 00001

10010 & 00001 = 00000 等价于十进制 0,为假,所以code3不会被执行。

这样我们就知道autoresizingMask 是怎么起作用的了。


实战演练:

在图文混排时,我么通常需要在一段文字中,检测是否有网络地址URL, 是否有表情符号Emoji,是否有电话号码,是否有邮箱等等。

typedef NS_OPTIONS(NSUInteger, FWDetectorTypes) {

FWDetectorTypesNone=0,

FWDetectorTypesURL=1<<0,  //1

FWDetectorTypesEmoji=1<<1,  //2

FWDetectorTypesPhoneNumber=1<<2,  //4

FWDetectorTypesEmail=1<<3,  //8

};

/**

需要识别的类型:默认识别表情

**/

@property(nonatomic,assign)FWDetectorTypes types;

如果我们只需要识别表情

types =FWDetectorTypesEmoji;

如果我们需要同时识别表情,电话,链接

types =FWDetectorTypesEmoji |FWDetectorTypesURL|FWDetectorTypesPhoneNumber

内部逻辑处理时:

if(types & FWDetectorTypesURL){

//识别链接逻辑代码

}

if(types & FWDetectorTypesEmoji){

//识别表情逻辑代码

}

if(types & FWDetectorTypesPhoneNumber){

//识别电话号码逻辑代码

}

if(types & FWDetectorTypesEmail){

//识别邮箱逻辑代码

}

明白三个运算符 左移(<<)、与(&)、或(|) 的运算法则,就能理解UIView的属性autoresizingMask

一个NSUInteger类型,为什么能枚举出许多种类型了。

上一篇下一篇

猜你喜欢

热点阅读