简体   繁体   中英

UIView alpha value compare error

At first, I set a view's alpha to 0.4, I want to some actions later when aView.alpha == 0.4, but the compare failed.

Code:

aView.alpha = 0.4;
...//never changes aView.alpha.
if (aView.alpha == 0.4) {
    //this compare failed.
}

BUT, when I set the alpha to 0.5, it works!

aView.alpha = 0.5;
...
if (aView.alpha == 0.5) {
    //it's OK.
}

Anything wrong?

Never compare floats using equality. It can work (apparently "positive zero" and "negative zero" are exact values) but you need to check that there is a very small difference, not that they are equal. Like:

#define TINY_DELTA (.0001f)

if(fabsf(floatA - floatB) < TINY_DELTA) {
    // equal for all intensive porpoises
}

(Actually you have doubles there. In general, use "0.5f" to use floats. It is generally faster on most of the hardware out there.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM