[心得] UIDevice - system version number

作者: whitefur (白毛)   2014-04-28 17:43:31
由於iOS 6 & 7有很多行為不同
甚至iOS 7.0 與 iOS 7.1也有不同的行為
ex1:
UINavigationBar
在iOS 6
tintColor 會作用到整條bar
但在iOS 7
則拆成 tintColor & barTintColor
=======
ex2:
UITextView - scrollEnabled = NO時
會自動產生NSContentSizeLayoutConstraint
2014-03-13 12:45:57.089 weiwha[2877:90b] contraint: (
"<NSContentSizeLayoutConstraint:0x116d6b850 H:[BubbleTextView:0x10e992080(132)] Hug:250 CompressionResistance:750>",
"<NSContentSizeLayoutConstraint:0x116d6b8b0 V:[BubbleTextView:0x10e992080(49)] Hug:250 CompressionResistance:750>"
))
scrollEnabled = YES 則不會有NSContentSizeLayoutConstraint
而此情形只在iOS 7.1出現
=====
於是為了要方便判斷iOS版本
我寫了一個UIDevice category
UIDevice 原來內建的 -systemVersion 為major.minor.build(ex:7.1.0)形式的NSString
我把它轉成major.minor的float(ex:7.1)
以方便比較版本
source code on github:
https://gist.github.com/WhiteFur/11366381
usage:
if([UIDevice currentDevice].sysVerNum >= 7.1)
//...do what you want....
=============
source code:
- (float)sysVerNum{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSString *sysVerStr = [UIDevice currentDevice].systemVersion;
NSError *error = nil;
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:@"\\d.\\d" options:0 error:&error];
if(error)
NSLog(@"UIDevice+SysVerNum sysVerNum regexp error: %@", error);
else{
NSTextCheckingResult *result = [regexp firstMatchInString:sysVerStr options:0 range:NSMakeRange(0, [sysVerStr length])];
NSString *resultStr = [sysVerStr substringWithRange:result.range];
NSNumberFormatter *numFormatter = [[NSNumberFormatter alloc] init];
numFormatter.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *sysVerNum = [numFormatter numberFromString:resultStr];
objc_setAssociatedObject(self, &SYS_VER_NUM_KEY, sysVerNum, OBJC_ASSOCIATION_RETAIN);
}
});
NSNumber *verNum = objc_getAssociatedObject(self, &SYS_VER_NUM_KEY);
return [verNum floatValue];
}

Links booklink

Contact Us: admin [ a t ] ucptt.com