typedef NS_OPTIONS检查像UIViewAutoresizing

app*_*pp_ 20 typedef ios

简要介绍我想要实现的目标:
我有一个自定义UIView,我想让箭头可见,例如在底部和左侧.我认为可以像这样做同样的方式UIViewAutoresizing.

所以我typedef为我的自定义视图创建了一个类似的:

typedef NS_OPTIONS(NSUInteger, Arrows) {
    ArrowNone      = 0,
    ArrowRight     = 1 << 0,
    ArrowBottom    = 1 << 1,
    ArrowLeft      = 1 << 2,
    ArrowTop       = 1 << 3
};
Run Code Online (Sandbox Code Playgroud)

另外在我的自定义视图头文件中,我添加了:

@property (nonatomic) Arrows arrows;
Run Code Online (Sandbox Code Playgroud)

这一切都有效,现在我可以设置属性:
customview.arrows = (ArrowBottom | ArrowLeft);

这回来了6.

现在是我的问题,如何检查我的arrows属性是否包含底部和左侧?我试过了:

if (self.arrows == ArrowLeft) {
    NSLog(@"Show arrow left");
}
Run Code Online (Sandbox Code Playgroud)

这没有做任何事情.还有另一种检查方法吗?

小智 36

检查位掩码的正确方法是使用AND(&)运算符解码值,如下所示:

Arrows a = (ArrowLeft | ArrowRight);    
if (a & ArrowBottom) {
   NSLog(@"arrow bottom code here");    
}

if (a & ArrowLeft) {
   NSLog(@"arrow left code here");    
}    

if (a & ArrowRight) {
   NSLog(@"arrow right code here");    
}

if (a & ArrowTop) {
   NSLog(@"arrow top code here");    
}
Run Code Online (Sandbox Code Playgroud)

这将在控制台中打印出来:

arrow left code here
arrow right code here
Run Code Online (Sandbox Code Playgroud)


小智 5

要进行复合检查,您可以使用以下代码:

if ((a & ArrowRight) && (a & ArrowTop)) {
       NSLog(@"arrow right and top code here");    
}
Run Code Online (Sandbox Code Playgroud)


小智 5

检查此值的正确方法是首先按位AND值,然后检查是否与所需值相等.

Arrows a = (ArrowBottom | ArrowLeft);    
if (((a & ArrowBottom) == ArrowBottom) && ((a & ArrowLeft) == ArrowLeft)) {
    // arrow bottom-left
}
Run Code Online (Sandbox Code Playgroud)

以下参考资料解释了为什么这是正确的,并提供了枚举类型的其他见解.

参考:检查位值掩码中的值