開(kāi)發(fā)中常用的一些工具

計(jì)算一個(gè)字符串的在一定寬度范圍內(nèi) 的 size

/*   計(jì)算文字的寬高
 *   param1:theString  需要計(jì)算的文字
 *   param2:aSize      文字在相應(yīng)載體(label、textView等)的字體
 *   param3:aWidth     展示文字的最大寬度
 */
+(CGSize)calculateText:(NSString *)theString font:(CGFloat)aSize maxWidth:(CGFloat)aWidth;

#pragma mark - 自動(dòng)計(jì)算文字的高度
+(CGSize)calculateText:(NSString *)theString font:(CGFloat)aSize maxWidth:(CGFloat)aWidth{
    
    NSDictionary *attrs = @{NSFontAttributeName : [UIFont systemFontOfSize:aSize]};
    
    CGRect rect = [theString boundingRectWithSize:CGSizeMake(aWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil];
    
    return rect.size;
}
/*   通過(guò)一個(gè)顏色值 得到一張圖片
 *   param1: 顏色
 *   param2: 圖片的尺寸
 */
+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size;

#pragma mark - 通過(guò)顏色值生產(chǎn)一張圖片
+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size{
    
    UIGraphicsBeginImageContext(size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    
    CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height));
    
    UIImage* theImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return theImage;
}

#pragma mark - 獲取設(shè)備型號(hào)
+(NSString *)getDeviceType{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
    NSString *path = [[NSBundle mainBundle]pathForResource:@"DeviceType" ofType:@"plist"];
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
    if ([[dict allKeys]containsObject:platform]) {
        return [dict objectForKey:platform];
    }else{
         return platform;
    }
}

#pragma mark - 檢測(cè)設(shè)備是否是iPad
+(BOOL)isiPad{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad){
        return TRUE;
    }
    return FALSE;
}

#pragma mark -檢測(cè)設(shè)備 是否越獄
+(BOOL)isJailBreak{
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"cydia://"]]) {
        return YES;
    }
    if ([[NSFileManager defaultManager] fileExistsAtPath:@"/User/Applications/"]) {
        return YES;
    }
    const char* jailbreak_tool_pathes[] = {
        "/Applications/Cydia.app",
        "/Library/MobileSubstrate/MobileSubstrate.dylib",
        "/bin/bash",
        "/usr/sbin/sshd",
        "/etc/apt"
    };
    for (int i=0; i<5; i++) {
        if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithUTF8String:jailbreak_tool_pathes[i]]]) {
            return YES;
        }
    }
    return NO;
}


#pragma mark -獲取當(dāng)前顯示的在屏幕上的控制器
+(UIViewController *)getTopController{
    UIViewController *topVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (topVC.presentedViewController) {
        topVC = topVC.presentedViewController;
    }
    return topVC;
}


#pragma mark - 檢測(cè)手機(jī)號(hào)碼
+(BOOL)isPhoneNumber:(NSString *)num{
    if (num.length < 11)
        return NO;
    NSString* regularExpression = @"^1[3|4|5|7|8][0-9]\\d{8}$";
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regularExpression];
    return [pre evaluateWithObject:num];
}

#pragma mark - 獲取設(shè)備的IDFA
+(NSString *)getDevice_IDFA{
     NSString *adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    if (adId) {
        return adId;
    }
    return @"";
}
#pragma mark - 獲取設(shè)備的UUID
+(NSString *)getDevice_UUID{
    if(NSClassFromString(@"NSUUID")) { // only available in iOS >= 6.0
        return [[NSUUID UUID] UUIDString];
    }
    CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
    CFStringRef cfuuid = CFUUIDCreateString(kCFAllocatorDefault, uuidRef);
    CFRelease(uuidRef);
    NSString *uuid = [((__bridge NSString *) cfuuid) copy];
    CFRelease(cfuuid);
    return uuid;
}


#pragma mark - 獲取設(shè)備的物理地址
+(NSString *)getDevice_MacAddress{
    int                 mib[6];
    size_t              len;
    char                *buf;
    unsigned char       *ptr;
    struct if_msghdr    *ifm;
    struct sockaddr_dl  *sdl;
    
    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;

    if ((mib[5] = if_nametoindex("en0")) == 0) {
        printf("Error: if_nametoindex error/n");
        return NULL;
    }
    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 1/n");
        return NULL;
    }
    if ((buf = malloc(len)) == NULL) {
        printf("Could not allocate memory. error!/n");
        return NULL;
    }
    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 2");
        return NULL;
    }
    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);
    NSString *outstring = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    free(buf);
    return [outstring uppercaseString];
}

#pragma mark - 獲取設(shè)備系統(tǒng)版本號(hào)
+ (NSString*)getDevice_iOSVersion{
    return  [[UIDevice currentDevice] systemVersion];
}

#pragma mark - 獲取設(shè)備系統(tǒng)電量
+(CGFloat )getDevice_batteryLevel{
   return  [[UIDevice currentDevice]batteryLevel];
}

#pragma mark - 獲取設(shè)備當(dāng)前網(wǎng)絡(luò)狀態(tài)
+(NSString *)getNetWorkStates{
    NSArray *arr = [[[[UIApplication sharedApplication] valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
    int type = 0;
    NSString *state = @"";
    for (id item in arr) {
        if ([item isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
            type = [[item valueForKeyPath:@"dataNetworkType"] intValue];
        }
    }
    switch (type) {
        case 1:{
            state = @"2G";
        }break;
        case 2:{
            state = @"3G";
        }break;
        case 3:{
            state = @"4G";
        }break;
        case 5:{
            state = @"WIFI";
        }
        default:{
            state = @"未知網(wǎng)絡(luò)";
        }break;
    }
    return state;
}


#pragma mark - 獲取設(shè)備當(dāng)前時(shí)間
+ (NSString *)getDevice_time{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    return [dateFormatter stringFromDate:[NSDate date]];
}
#pragma mark - 獲取應(yīng)用的包名
+(NSString *)getApplication_BundleIdentify{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    return [infoDictionary objectForKey:@"CFBundleIdentifier"];
}

#pragma mark - 獲取項(xiàng)目名稱
+ (NSString*)getApplication_projectName{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    return [infoDictionary objectForKey:@"CFBundleName"];
}

#pragma mark - 獲取項(xiàng)目版本號(hào)
+ (CGFloat)getApplication_version{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    return [[infoDictionary objectForKey:@"CFBundleVersion"] floatValue];
}
//將 數(shù)值 按千位分隔符的方式分隔開(kāi)
+(NSString *)PriceFormateWithPrice:(NSString *)price
{
    NSNumberFormatter *matter = [[NSNumberFormatter alloc]init];
    [matter setPositiveFormat:@"###,###,##0.00"];
    NSString *result = [matter stringFromNumber:[NSNumber numberWithDouble:[price doubleValue]]];
    result = [@"¥" stringByAppendingString:result];
    return result;
}

歡迎廣大 程序開(kāi)發(fā)愛(ài)好者來(lái)補(bǔ)充讓以后的開(kāi)發(fā)多一些工具 少一些羈絆!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,872評(píng)論 25 709
  • linux資料總章2.1 1.0寫的不好抱歉 但是2.0已經(jīng)改了很多 但是錯(cuò)誤還是無(wú)法避免 以后資料會(huì)慢慢更新 大...
    數(shù)據(jù)革命閱讀 13,199評(píng)論 2 33
  • 今天是小年,臘月二十三,距離除夕還有七天?;蛟S在遠(yuǎn)方工作或求學(xué)的朋友已經(jīng)陸續(xù)踏上返鄉(xiāng)的旅途,父母在家早已經(jīng)開(kāi)始...
    笨大儒閱讀 229評(píng)論 0 1
  • 1.下載pyqt,qt,sip qt: http://mirrors.ustc.edu.cn/qtproject/...
    燦爛的望天樹(shù)閱讀 2,357評(píng)論 0 0
  • 你翹著二郎腿 呆呆的望著天花板 手里夾著根煙 煙霧從你嘴里吐出 象漣漪般在空氣中慢慢散開(kāi)…… 也許 你自以為很酷 ...
    天水居士閱讀 196評(píng)論 6 6

友情鏈接更多精彩內(nèi)容