A short introduction to what I want to achieve with this:
I've a custom UIView
where I want to make arrows visible, for example on bottom and left side.
I thought it would be possible to do this the same way as UIViewAutoresizing
does it.
So I created a similar typedef
for my custom view:
typedef NS_OPTIONS(NSUInteger, Arrows) {
ArrowNone = 0,
ArrowRight = 1 << 0,
ArrowBottom = 1 << 1,
ArrowLeft = 1 << 2,
ArrowTop = 1 << 3
};
Also in my custom view header file, I added:
@property (nonatomic) Arrows arrows;
This all works and now I'm able to set the property:
customview.arrows = (ArrowBottom | ArrowLeft);
This returns 6
.
Now's my question, how can check if my arrows
property contains bottom and left?
I tried:
if (self.arrows == ArrowLeft) {
NSLog(@"Show arrow left");
}
This didn't do anything. Is there another way to check this?
The right way to check your bitmask is by decoding the value using the AND (&) operator as follows:
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");
}
This will print out in the console:
arrow left code here
arrow right code here
To do a compound check you could use the following code:
if ((a & ArrowRight) && (a & ArrowTop)) {
NSLog(@"arrow right and top code here");
}
The correct way to check for this value is to first bitwise AND the values and then check for equality to the required value.
Arrows a = (ArrowBottom | ArrowLeft);
if (((a & ArrowBottom) == ArrowBottom) && ((a & ArrowLeft) == ArrowLeft)) {
// arrow bottom-left
}
The following reference explains why this is correct and provides other insights into enumerated types.
Reference: checking-for-a-value-in-a-bit-mask
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With