自己常用的工具类

自己常用的工具类

///本地保存string,int,Char,等类型,forKey为键,Value为要保存的值

+ (void)UserDefaultSetValue:(id)Value forKey:(NSString *)keyString;

///本地保存BOOL类型,forKey为键,Value为要保存的值

+ (void)UserDefaultSetBool:(BOOL )VBool forKey:(NSString *)keyString;

///删除本地保存的值,keyString为键

+ (void)UserDefaultRemoveObjectForKey:(NSString *)keyString;

///取出本地保存的string,int,Char,等值,keyString为键

+ (id)UserDefaultObjectForKey:(NSString *)keyString;

///取出本地保存BOOL类型,forKey为键

+ (BOOL)UserDefaultBoolForKey:(NSString *)keyString;


+ (NSMutableAttributedString *)stringChangeAttributeColor:(NSString *)textString andColor:(UIColor *)fontColor and:(NSUInteger)rangeLen;

///把textString,从尾部反向改变长度range,范围的字体颜色

+ (NSMutableAttributedString *)stringChangeEndAttributeColor:(NSString *)textString andColor:(UIColor *)fontColor and:(NSUInteger)range;

///把textString,缩进CGFloat类型15或20

+ (NSMutableAttributedString *)stringHeadIndentAttribute:(NSString *)textString andIndent:(CGFloat)Indent;

///label 自动换行 修改字体大小

+(void)lableWordWrap:(UILabel *)label andfont:(int)font;

///根据字体长度返回宽度

+ (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxSize:(CGSize)maxSize;

///特殊的,为了计算评价cell的高度

+ (CGFloat)cellHeightfortextString:(NSString *)textString Images:(NSInteger)Nums;

///计算字体大小为14.f的String高度,上下加了15

+ (CGFloat)toCellTextHeight:(NSString *)String;

///判断是否是正确的手机号

+ (BOOL)PredicateJudgeTelePhone:(NSString *)telePhone;

///计算本地缓存大小

+ (float)allFileSizeLocalCache;

///清理本地缓存

+ (void)cleanAllFileSizeLocalCache;

///把数组保存到本地存储为plist文件里,并给出plist文件名字

+ (void)FileNSArrayStorageToPlist:(NSArray *)fileArray PlistName:(NSString *)plistName;

///从plist文件里读出数组,必须保证plist文件内的确存的是数组!

+ (NSArray *)FileReadNsArrayFromPlist:(NSString *)plistName;

///删除本地缓存的plist文件

+ (void)FileManagerDeletePlistfile:(NSString *)plistName;

///时间转换法则 yyyy-MM-dd HH-mm-ss

+(NSString *)StringFromDateHHmmss:(long) value;

///通过时间戳yyyy-MM-dd

+(NSString *)StringFromDateMMDD:(long)value;

///通过时间戳找到今天周几

+ (NSString *)FindWeekThroughTimestam:(long) value;

///判断当前网络

+ (BOOL)isConnectionAvailable;

///时间转换法则 yyyy-MM-dd

+ (NSDate *)dateFromDateAabAdd:(NSDate *)oldDate;

///时间转换法则 yyyy-MM-dd HH-mm-ss

+ (NSDate *)dateFromDateHHmmss:(NSDate *)oldDate;

///时间转换 未加8小时

+ (NSDate *)dateDateHHmmss:(NSDate *)Date;

///获取时间Date的年-月-日-时-分-秒,返回在数组中

+ (NSArray *)ArrayFromDateComponents:(NSDate *)date;

///根据时间格式Date返回String:年-月-日

+ (NSString *)stringFromDateSubLength:(NSDate *)currentDate;

///计算加减天,返回时间Date格式.string为年-月-日,加为YES,numMonth为增减天数1,7

+ (NSDate *)dateFromDateString:(NSString *)dateString AddDate:(BOOL)addBool andNum:(NSUInteger )dayNum;

///计算加减月份,返回时间Date格式.string为年-月-日,加为YES,numMonth为增减月量1-12

+ (NSDate*)nextMonthDateFromTextString:(NSString *)dateString AddBooL:(BOOL)addBool monthNum:(NSInteger)numMonth;

///将十六进制颜色转换为 UIColor 对象,string要加#,如“#c83c23”

+ (UIColor *)colorWithHexString:(NSString *)color;

///提示框  message 为提示信息

+(void)alterViewShow:(NSString *)message viewcontroller:(UIViewController *)controller stayTime:(int)time;

///去除(null)

+ (NSString *) isBlankString:(NSString *)string;

+ (long)isBlankLong:(long)lng;

///获取Label的高度

+ (CGFloat)getHeightByWidth:(CGFloat)width title:(NSString *)title font:(UIFont*)font;

///获取Label的宽度

+ (CGFloat)getWidthWithTitle:(NSString *)title font:(UIFont *)font;

///压缩图片

+ (NSData *)compressdePNGImage:(UIImage *)image;

// 重绘图片大小

+ (UIImage *)imageWithPNGImage:(UIImage*)image scaledToSize:(CGSize)newSize;


具体实现方法


///压缩图片

+ (NSData *)compressdeImage:(UIImage *)image{


    CGSize imagesize =image.size;

    imagesize.height =imagesize.height/4;

    imagesize.width =imagesize.width/4;

    UIImage * imageNew = [self imageWithImage:image scaledToSize:imagesize];


    return  UIImageJPEGRepresentation(imageNew, 1);

}

// 重绘图片大小

+ (UIImage *)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize{


    UIGraphicsBeginImageContext(newSize);

    //重绘

    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];

    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();


    return newImage;


}

+ (void)UserDefaultSetValue:(id)Value forKey:(NSString *)keyString{

    NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults];

    if (![Value isKindOfClass:[NSNull class]]) {

        [userDefault setValue:Value forKey:keyString];

    }else {

        [userDefault setValue:@"" forKey:keyString];

    }

    [userDefault synchronize];

}

+ (void)UserDefaultSetBool:(BOOL )VBool forKey:(NSString *)keyString{

    NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults];

    [userDefault setBool:VBool forKey:keyString];

    [userDefault synchronize];

}

+ (void)UserDefaultRemoveObjectForKey:(NSString *)keyString {

    NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults];

    [userDefault removeObjectForKey:keyString];

    [userDefault synchronize];

}

+ (id)UserDefaultObjectForKey:(NSString *)keyString {

    NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults];

    NSString * string = [userDefault objectForKey:keyString];


    [[NSUserDefaults standardUserDefaults] objectForKey:@""];

    return string;

}

+ (BOOL)UserDefaultBoolForKey:(NSString *)keyString {

    NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults];

    BOOL Bool= [userDefault boolForKey:keyString];


    return Bool;

}

+ (NSMutableAttributedString *)stringAddThroughLines:(NSString *)textString and:(NSUInteger)rangeLoc{

    NSMutableAttributedString *AttributedString = [[NSMutableAttributedString alloc] initWithString:textString];

    [AttributedString addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(rangeLoc, textString.length-rangeLoc)];

    return AttributedString;

}

+ (NSMutableAttributedString *)stringChangeAttributeFont:(NSString *)textString andSize:(CGFloat)fontSize and:(NSUInteger)rangeLen

{

    NSMutableAttributedString *AttributedString = [[NSMutableAttributedString alloc] initWithString:textString];

    [AttributedString addAttribute:NSFontAttributeName

                            value:[UIFont systemFontOfSize:fontSize]

                            range:NSMakeRange(0, rangeLen)];


    return AttributedString;

}

+ (NSMutableAttributedString *)stringChangeEndAttributeFont:(NSString *)textString andSize:(CGFloat)fontSize endRang:(NSUInteger)endRange

{

    NSMutableAttributedString *AttributedString = [[NSMutableAttributedString alloc] initWithString:textString];

    [AttributedString addAttribute:NSFontAttributeName

                            value:[UIFont systemFontOfSize:fontSize]

                            range:NSMakeRange(textString.length-endRange, endRange)];


    return AttributedString;

}

+ (NSMutableAttributedString *)stringChangeAttributeFontColor:(NSString *)textString andSize:(CGFloat)fontSize andColor:(UIColor *)fontColor and:(NSUInteger)rangeLen

{

    NSMutableAttributedString *AttributedString = [[NSMutableAttributedString alloc] initWithString:textString];

    [AttributedString addAttribute:NSFontAttributeName

                            value:[UIFont systemFontOfSize:fontSize]

                            range:NSMakeRange(0, rangeLen)];

    [AttributedString addAttribute:NSForegroundColorAttributeName

                            value:fontColor

                            range:NSMakeRange(0, rangeLen)];

    return AttributedString;

}

+ (NSMutableAttributedString *)stringChangeEndAttributeFontColor:(NSString *)textString andSize:(CGFloat)fontSize andColor:(UIColor *)fontColor and:(NSUInteger)range

{

    NSMutableAttributedString *AttributedString = [[NSMutableAttributedString alloc] initWithString:textString];

    [AttributedString addAttribute:NSFontAttributeName

                            value:[UIFont systemFontOfSize:fontSize]

                            range:NSMakeRange(textString.length-range, range)];

    [AttributedString addAttribute:NSForegroundColorAttributeName

                            value:fontColor

                            range:NSMakeRange(textString.length-range, range)];

    return AttributedString;

}

+ (NSMutableAttributedString *)stringChangeAttributeColor:(NSString *)textString andColor:(UIColor *)fontColor and:(NSUInteger)rangeLen

{

    NSMutableAttributedString *AttributedString = [[NSMutableAttributedString alloc] initWithString:textString];

    [AttributedString addAttribute:NSForegroundColorAttributeName

                            value:fontColor

                            range:NSMakeRange(0, rangeLen)];

    return AttributedString;

}

+ (NSMutableAttributedString *)stringChangeEndAttributeColor:(NSString *)textString andColor:(UIColor *)fontColor and:(NSUInteger)range

{

    NSMutableAttributedString *AttributedString = [[NSMutableAttributedString alloc] initWithString:textString];

    [AttributedString addAttribute:NSForegroundColorAttributeName

                            value:fontColor

                            range:NSMakeRange(textString.length-range, range)];

    return AttributedString;

}

+ (NSMutableAttributedString *)stringHeadIndentAttribute:(NSString *)textString andIndent:(CGFloat)Indent

{

    NSMutableAttributedString *AttributedString = [[NSMutableAttributedString alloc] initWithString:textString];

    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];

    style.firstLineHeadIndent = Indent;

    //    style.headIndent = Indent;//整体缩进

//        style.lineSpacing = 3.f;//行距

    [AttributedString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, AttributedString.length)];

    return AttributedString;

}

+ (CGFloat)cellHeightfortextString:(NSString *)textString Images:(NSInteger)Nums{

    CGFloat height =49+30+5;

    if (Nums ==0) {

        height +=0.f;

    }else{

        height +=80.f;

    }

    if (![textString isKindOfClass:[NSNull class]]) {

        CGFloat TextHeight = [textString sizeWithFont:[UIFont systemFontOfSize:14.f] Size:CGSizeMake([[UIScreen mainScreen] bounds].size.width- 48-8, MAXFLOAT)].height;

        height +=TextHeight+1;

    }

    return height;

}

+ (CGFloat)toCellTextHeight:(NSString *)String{

    CGFloat height =10;

    if (![String isKindOfClass:[NSNull class]]) {

        CGFloat TextHeight = [String sizeWithFont:[UIFont systemFontOfSize:14.f] Size:CGSizeMake([[UIScreen mainScreen] bounds].size.width-16, MAXFLOAT)].height;

        height +=TextHeight+1;

    }

    return height+8;

}

+ (BOOL)PredicateJudgeTelePhone:(NSString *)telePhone {

    NSString * num = @"^1[3|4|5|7|8][0-9]\\d{8}$";

    NSPredicate *regextestnum = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",num];


    if ([regextestnum evaluateWithObject:telePhone]){

        return YES;

    }else{

        return NO;

    }

}

+ (float)allFileSizeLocalCache{

    NSString *filepath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

    NSFileManager *fileManager=[NSFileManager defaultManager];

    __block float folderSize =0;

    if ([fileManager fileExistsAtPath:filepath]) {

        //拿到算有文件的数组

        NSArray *filesArray = [fileManager subpathsAtPath:filepath];

        [filesArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

            NSString *fullPath = [filepath stringByAppendingPathComponent:obj];

            folderSize += [self fileSizeAtPath:fullPath];

        }];

        //拿到每个文件的名字,如有有不想清除的文件就在这里判断

    }

    return folderSize;

}

+ (void)cleanAllFileSizeLocalCache{

    NSString *filepath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

    NSFileManager *fileManager=[NSFileManager defaultManager];

    if ([fileManager fileExistsAtPath:filepath]) {

        //拿到算有文件的数组

        NSArray *filesArray = [fileManager subpathsAtPath:filepath];

        [filesArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

            NSString *fullPath = [filepath stringByAppendingPathComponent:obj];

            [fileManager removeItemAtPath:fullPath error:nil];

        }];

        //拿到每个文件的名字,如有有不想清除的文件就在这里判断

    }

}

+ (float)fileSizeAtPath:(NSString *)path{


    NSFileManager *fileManager=[NSFileManager defaultManager];


    if([fileManager fileExistsAtPath:path]){ ///判断


        long long size=[fileManager attributesOfItemAtPath:path error:nil].fileSize;

        return size/1024.0/1024.0;

    }


    return 0;

}

+ (void)FileNSArrayStorageToPlist:(NSArray *)fileArray PlistName:(NSString *)plistName{

    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;

    NSString *fileName = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@",plistName,@".plist"]];

    [fileArray writeToFile:fileName atomically:YES];

}

+ (NSArray *)FileReadNsArrayFromPlist:(NSString *)plistName{

    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;

    NSString *filePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@",plistName,@".plist"]];

    return [NSArray arrayWithContentsOfFile:filePath];

}

+ (void)FileManagerDeletePlistfile:(NSString *)plistName{

    NSFileManager *fManager = [NSFileManager defaultManager];

    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;

    NSString *filePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@",plistName,@".plist"]];

    [fManager removeItemAtPath:filePath error:nil];

}

+ (NSDate *)dateFromDateAabAdd:(NSDate *)oldDate{


    NSDateFormatter *dateFormatter =[[NSDateFormatter alloc]init];


    [dateFormatter setDateFormat:@"yyyy-MM-dd 00:00:00"];

    NSString *stringdate =[dateFormatter stringFromDate:oldDate];

    oldDate =[dateFormatter dateFromString:stringdate];

    NSTimeInterval intervalTime = [oldDate timeIntervalSince1970];

    intervalTime =intervalTime +(8*60*60);

    NSDate *newDate = [NSDate dateWithTimeIntervalSince1970:intervalTime];

    return newDate;

}

+ (NSDate *)dateFromDateHHmmss:(NSDate *)oldDate{


    NSDateFormatter *dateFormatter =[[NSDateFormatter alloc]init];


    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSString *stringdate =[dateFormatter stringFromDate:oldDate];

    oldDate =[dateFormatter dateFromString:stringdate];

    NSTimeInterval intervalTime = [oldDate timeIntervalSince1970];

    intervalTime =intervalTime +(8*60*60);

    NSDate *newDate = [NSDate dateWithTimeIntervalSince1970:intervalTime];

    return newDate;

}

+ (NSDate *)dateDateHHmmss:(NSDate *)Date{

    NSDateFormatter *dateFormatter =[[NSDateFormatter alloc]init];


    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSString *stringdate =[dateFormatter stringFromDate:Date];

    Date =[dateFormatter dateFromString:stringdate];


    return Date;

}

+ (NSArray *)ArrayFromDateComponents:(NSDate *)date{

    NSMutableArray *dateArray =[NSMutableArray array];

    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitHour| NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:date];


    NSInteger dateYear  = [components year];

    NSInteger dateMonth = [components month];

    NSInteger dateDay  = [components day];

    NSInteger dateHour  = [components hour];

    NSInteger dateMinute  = [components minute];

    NSInteger dateSecond  = [components second];


    NSNumber *yearVal=[NSNumber numberWithInteger:dateYear];

    NSNumber *monthVal=[NSNumber numberWithInteger:dateMonth];

    NSNumber *dayVal=[NSNumber numberWithInteger:dateDay];

    NSNumber *hourVal=[NSNumber numberWithInteger:dateHour];

    NSNumber *minuteVal=[NSNumber numberWithInteger:dateMinute];

    NSNumber *secondVal=[NSNumber numberWithInteger:dateSecond];

    [dateArray addObject:yearVal];

    [dateArray addObject:monthVal];

    [dateArray addObject:dayVal];

    [dateArray addObject:hourVal];

    [dateArray addObject:minuteVal];

    [dateArray addObject:secondVal];


    return dateArray;

}

+ (NSString *)stringFromDateSubLength:(NSDate *)currentDate{

    NSString *dataStr=[NSString stringWithFormat:@"%@",[NineStarToolsObject dateFromDateAabAdd:currentDate]];

    dataStr= [dataStr substringToIndex:dataStr.length -15];

    return dataStr;

}

+ (NSDate *)dateFromDateString:(NSString *)dateString AddDate:(BOOL)addBool andNum:(NSUInteger )dayNum{

    NSDateFormatter *dateFormatter =[[NSDateFormatter alloc]init];

    [dateFormatter setDateFormat:@"yyyy-MM-dd 00:00:00"];

    NSDate  *oldDate =[dateFormatter dateFromString:dateString];

    NSTimeInterval intervalTime = [oldDate timeIntervalSince1970];

    if (addBool) {

        intervalTime =intervalTime +dayNum*(24*60*60)+(8*60*60);

    }else{

        intervalTime =intervalTime -dayNum*(24*60*60)+(8*60*60);

    }

    NSDate *newDate = [NSDate dateWithTimeIntervalSince1970:intervalTime];

    return newDate;

}

+ (NSDate*)nextMonthDateFromTextString:(NSString *)dateString AddBooL:(BOOL)addBool monthNum:(NSInteger)numMonth{

    NSDateFormatter *dateFormatter =[[NSDateFormatter alloc]init];

    [dateFormatter setDateFormat:@"yyyy-MM-dd 00:00:00"];

    NSDate  *oldDate =[dateFormatter dateFromString:dateString];

    NSTimeInterval intervalTime = [oldDate timeIntervalSince1970];

    intervalTime =intervalTime +(8*60*60);

    oldDate = [NSDate dateWithTimeIntervalSince1970:intervalTime];

    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];

    if (addBool) {

        dateComponents.month = + numMonth;

    }else{

        dateComponents.month = - numMonth;

    }

    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:oldDate options:0];

    return newDate;

}

+(NSString *)StringFromDateHHmmss:(long) value{

    NSString *str1=[NSString stringWithFormat:@"%ld",value];


    long x=[[str1 substringToIndex:10] longLongValue];


    NSDate  *newDate = [NSDate dateWithTimeIntervalSince1970:x];


    NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init];


    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm"];

    NSString *ymdhmStr= [dateformatter stringFromDate:newDate];

    return ymdhmStr;

}

+(NSString *)StringFromDateMMDD:(long)value{


    NSString *str1=[NSString stringWithFormat:@"%ld",value];


    long x=[[str1 substringToIndex:10] longLongValue];


    NSDate  *newDate = [NSDate dateWithTimeIntervalSince1970:x];


    NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init];


    [dateformatter setDateFormat:@"yyyy-MM-dd"];

    NSString *ymdhmStr= [dateformatter stringFromDate:newDate];

    return ymdhmStr;


}

+ (NSString *)FindWeekThroughTimestam:(long) value{

    NSString *str1=[NSString stringWithFormat:@"%ld",value];

    long data =[[str1 substringToIndex:10] longLongValue];

    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;

    NSDate *newDate = [NSDate dateWithTimeIntervalSince1970:data];

    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:newDate];

    NSString *weekStr = [weekdays objectAtIndex:theComponents.weekday];


    return weekStr;

}

+ (BOOL)isConnectionAvailable{

    BOOL isExistenceNetwork = YES;

    Reachability *reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];

    switch ([reach currentReachabilityStatus]) {

        case NotReachable:

            isExistenceNetwork = NO;

            //NSLog(@"notReachable");

            break;

        case ReachableViaWiFi:

            isExistenceNetwork = YES;

            //NSLog(@"WIFI");

            break;

        case ReachableViaWWAN:

            isExistenceNetwork = YES;

            //NSLog(@"3G");

            break;

    }

    return isExistenceNetwork;

}

+ (UIColor *)colorWithHexString:(NSString *)color{

    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

    // String should be 6 or 8 characters

    if ([cString length] < 6) {

        return [UIColor clearColor];

    }

    // strip "0X" or "#" if it appears

    if ([cString hasPrefix:@"0X"])

        cString = [cString substringFromIndex:2];

    if ([cString hasPrefix:@"#"])

        cString = [cString substringFromIndex:1];

    if ([cString length] != 6)

        return [UIColor clearColor];

    // Separate into r, g, b substrings

    NSRange range;

    range.location = 0;

    range.length = 2;

    //r

    NSString *rString = [cString substringWithRange:range];

    //g

    range.location = 2;

    NSString *gString = [cString substringWithRange:range];

    //b

    range.location = 4;

    NSString *bString = [cString substringWithRange:range];

    // Scan values

    unsigned int r, g, b;

    [[NSScanner scannerWithString:rString] scanHexInt:&r];

    [[NSScanner scannerWithString:gString] scanHexInt:&g];

    [[NSScanner scannerWithString:bString] scanHexInt:&b];

    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];

}

+(void)alterViewShow:(NSString *)message viewcontroller:(UIViewController *)controller  stayTime:(int)time{

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];

    [controller presentViewController:alert animated:YES completion:^{

        //延迟1秒自动消失

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            [alert dismissViewControllerAnimated:YES completion:nil];

        });

    }];

}

+ (NSString *)isBlankString:(NSString *)string {

    if (string == nil || string == NULL || string == 0) {

        return @"";

    }

    if ([string isKindOfClass:[NSNull class]]) {

        return @"";

    }

    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {

        return @"";

    }

    return string;

}

+ (long)isBlankLong:(long)lng{

    if (lng ==0 ) {

        return (long)@"";

    }

    return lng;

}

+(void)lableWordWrap:(UILabel *)label andfont:(int)font{

    label.numberOfLines =0 ;

    label.lineBreakMode = NSLineBreakByWordWrapping;

    if (font!=0) {

        label.font = [UIFont systemFontOfSize:font];

    }


}

+ (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxSize:(CGSize)maxSize

    NSDictionary *attrs = @{NSFontAttributeName : font};

    return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;

}

+ (CGFloat)getHeightByWidth:(CGFloat)width title:(NSString *)title font:(UIFont *)font

{


    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 0)];

    label.text = title;

    label.font = font;

    label.numberOfLines = 0;

    [label sizeToFit];

    CGFloat height = label.frame.size.height;

    return height;

}

+ (CGFloat)getWidthWithTitle:(NSString *)title font:(UIFont *)font {

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 1000, 0)];

    label.text = title;

    label.font = font;

    [label sizeToFit];

    return label.frame.size.width;

}

///压缩图片

+ (NSData *)compressdePNGImage:(UIImage *)image{


    CGSize imagesize =image.size;

    imagesize.height =imagesize.height/4;

    imagesize.width =imagesize.width/4;

    UIImage * imageNew = [self imageWithPNGImage:image scaledToSize:imagesize];


    return  UIImagePNGRepresentation(imageNew);


}

// 重绘图片大小

+ (UIImage *)imageWithPNGImage:(UIImage*)image scaledToSize:(CGSize)newSize{


    UIGraphicsBeginImageContext(newSize);

    //重绘

    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];

    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();


    return newImage;


}

你可能感兴趣的:(自己常用的工具类)