文档章节

iOS 公用方法

m
 miaoshijun
发布于 2016/07/26 11:27
字数 9245
阅读 8
收藏 0
点赞 0
评论 0

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

//磁盘总空间

+ (CGFloat)diskOfAllSizeMBytes{

    CGFloat size = 0.0;

    NSError *error;

    NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];

    if (error) {

#ifdef DEBUG

        NSLog(@"error: %@", error.localizedDescription);

#endif

    }else{

        NSNumber *number = [dic objectForKey:NSFileSystemSize];

        size = [number floatValue]/1024/1024;

    }

    return size;

}




2. 获取磁盘可用空间大小

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

//磁盘可用空间

+ (CGFloat)diskOfFreeSizeMBytes{

    CGFloat size = 0.0;

    NSError *error;

    NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];

    if (error) {

#ifdef DEBUG

        NSLog(@"error: %@", error.localizedDescription);

#endif

    }else{

        NSNumber *number = [dic objectForKey:NSFileSystemFreeSize];

        size = [number floatValue]/1024/1024;

    }

    return size;

}





3. 获取指定路径下某个文件的大小

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

//获取文件大小

+ (long long)fileSizeAtPath:(NSString *)filePath{

    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath:filePath]) return 0;

    return [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];

}





4. 获取文件夹下所有文件的大小

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

//获取文件夹下所有文件的大小

+ (long long)folderSizeAtPath:(NSString *)folderPath{

    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath:folderPath]) return 0;

    NSEnumerator *filesEnumerator = [[fileManager subpathsAtPath:folderPath] objectEnumerator];

    NSString *fileName;

    long long folerSize = 0;

    while ((fileName = [filesEnumerator nextObject]) != nil) {

        NSString *filePath = [folderPath stringByAppendingPathComponent:fileName];

        folerSize += [self fileSizeAtPath:filePath];

    }

    return folerSize;

}




5. 获取字符串(或汉字)首字母

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

8

//获取字符串(或汉字)首字母

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

    NSMutableString *str = [NSMutableString stringWithString:string];

    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);

    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);

    NSString *pingyin = [str capitalizedString];

    return [pingyin substringToIndex:1];

}







6. 将字符串数组按照元素首字母顺序进行排序分组

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

//将字符串数组按照元素首字母顺序进行排序分组

+ (NSDictionary *)dictionaryOrderByCharacterWithOriginalArray:(NSArray *)array{

    if (array.count == 0) {

        return nil;

    }

    for (id obj in array) {

        if (![obj isKindOfClass:[NSString class]]) {

            return nil;

        }

    }

    UILocalizedIndexedCollation *indexedCollation = [UILocalizedIndexedCollation currentCollation];

    NSMutableArray *objects = [NSMutableArray arrayWithCapacity:indexedCollation.sectionTitles.count];

    //创建27个分组数组

    for (int i = 0; i < indexedCollation.sectionTitles.count; i++) {

        NSMutableArray *obj = [NSMutableArray array];

        [objects addObject:obj];

    }

    NSMutableArray *keys = [NSMutableArray arrayWithCapacity:objects.count];

    //按字母顺序进行分组

    NSInteger lastIndex = -1;

    for (int i = 0; i < array.count; i++) {

        NSInteger index = [indexedCollation sectionForObject:array[i] collationStringSelector:@selector(uppercaseString)];

        [[objects objectAtIndex:index] addObject:array[i]];

        lastIndex = index;

    }

    //去掉空数组

    for (int i = 0; i < objects.count; i++) {

        NSMutableArray *obj = objects[i];

        if (obj.count == 0) {

            [objects removeObject:obj];

        }

    }

    //获取索引字母

    for (NSMutableArray *obj in objects) {

        NSString *str = obj[0];

        NSString *key = [self firstCharacterWithString:str];

        [keys addObject:key];

    }

    NSMutableDictionary *dic = [NSMutableDictionary dictionary];

    [dic setObject:objects forKey:keys];

    return dic;

}

 

//获取字符串(或汉字)首字母

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

    NSMutableString *str = [NSMutableString stringWithString:string];

    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);

    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);

    NSString *pingyin = [str capitalizedString];

    return [pingyin substringToIndex:1];

}

使用如下:

[Objective-C] 查看源文件 复制代码

?

1

2

3

NSArray *arr = @[@"guangzhou", @"shanghai", @"北京", @"henan", @"hainan"];

NSDictionary *dic = [Utilities dictionaryOrderByCharacterWithOriginalArray:arr];

NSLog(@"\n\ndic: %@", dic);


 

输出结果如下:

 
输出结果


7. 获取当前时间

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

//获取当前时间

//format: @"yyyy-MM-dd HH:mm:ss"、@"yyyy年MM月dd日 HH时mm分ss秒"

+ (NSString *)currentDateWithFormat:(NSString *)format{

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

    [dateFormatter setDateFormat:format];

    return [dateFormatter stringFromDate:[NSDate date]];

}






8. 计算上次日期距离现在多久, 如 xx 小时前、xx 分钟前等

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

/**

 *  计算上次日期距离现在多久

 *

 *  @param lastTime    上次日期(需要和格式对应)

 *  @param format1     上次日期格式

 *  @param currentTime 最近日期(需要和格式对应)

 *  @param format2     最近日期格式

 *

 *  @return xx分钟前、xx小时前、xx天前

 */

+ (NSString *)timeIntervalFromLastTime:(NSString *)lastTime

                        lastTimeFormat:(NSString *)format1

                         ToCurrentTime:(NSString *)currentTime

                     currentTimeFormat:(NSString *)format2{

    //上次时间

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

    dateFormatter1.dateFormat = format1;

    NSDate *lastDate = [dateFormatter1 dateFromString:lastTime];

    //当前时间

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

    dateFormatter2.dateFormat = format2;

    NSDate *currentDate = [dateFormatter2 dateFromString:currentTime];

    return [Utilities timeIntervalFromLastTime:lastDate ToCurrentTime:currentDate];

}

 

+ (NSString *)timeIntervalFromLastTime:(NSDate *)lastTime ToCurrentTime:(NSDate *)currentTime{

    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];

    //上次时间

    NSDate *lastDate = [lastTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:lastTime]];

    //当前时间

    NSDate *currentDate = [currentTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:currentTime]];

    //时间间隔

    NSInteger intevalTime = [currentDate timeIntervalSinceReferenceDate] - [lastDate timeIntervalSinceReferenceDate];

 

    //秒、分、小时、天、月、年

    NSInteger minutes = intevalTime / 60;

    NSInteger hours = intevalTime / 60 / 60;

    NSInteger day = intevalTime / 60 / 60 / 24;

    NSInteger month = intevalTime / 60 / 60 / 24 / 30;

    NSInteger yers = intevalTime / 60 / 60 / 24 / 365;

 

    if (minutes <= 10) {

        return  @"刚刚";

    }else if (minutes < 60){

        return [NSString stringWithFormat: @"%ld分钟前",(long)minutes];

    }else if (hours < 24){

        return [NSString stringWithFormat: @"%ld小时前",(long)hours];

    }else if (day < 30){

        return [NSString stringWithFormat: @"%ld天前",(long)day];

    }else if (month < 12){

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

        df.dateFormat = @"M月d日";

        NSString * time = [df stringFromDate:lastDate];

        return time;

    }else if (yers >= 1){

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

        df.dateFormat = @"yyyy年M月d日";

        NSString * time = [df stringFromDate:lastDate];

        return time;

    }

    return @"";

}



 

使用如下:

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

NSLog(@"\n\nresult: %@", [Utilities timeIntervalFromLastTime:@"2015年12月8日 15:50"

                                           lastTimeFormat:@"yyyy年MM月dd日 HH:mm"

                                            ToCurrentTime:@"2015/12/08 16:12"

                                        currentTimeFormat:@"yyyy/MM/dd HH:mm"]);






 

输出结果如下:

 
输出结果


9. 判断手机号码格式是否正确

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

//判断手机号码格式是否正确

+ (BOOL)valiMobile:(NSString *)mobile{

    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];

    if (mobile.length != 11)

    {

        return NO;

    }else{

        /**

         * 移动号段正则表达式

         */

        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";

        /**

         * 联通号段正则表达式

         */

        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";

        /**

         * 电信号段正则表达式

         */

        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";

        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];

        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];

        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];

        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];

        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];

        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];

 

        if (isMatch1 || isMatch2 || isMatch3) {

            return YES;

        }else{

            return NO;

        }

    }

}






10. 判断邮箱格式是否正确

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

//利用正则表达式验证

+ (BOOL)isAvailableEmail:(NSString *)email {

    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";

    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];

    return [emailTest evaluateWithObject:email];

}





11. 将十六进制颜色转换为 UIColor 对象

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

//将十六进制颜色转换为 UIColor 对象

+ (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];

}





12. 对图片进行滤镜处理

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

#pragma mark - 对图片进行滤镜处理

// 怀旧 --> CIPhotoEffectInstant                         单色 --> CIPhotoEffectMono

// 黑白 --> CIPhotoEffectNoir                            褪色 --> CIPhotoEffectFade

// 色调 --> CIPhotoEffectTonal                           冲印 --> CIPhotoEffectProcess

// 岁月 --> CIPhotoEffectTransfer                        铬黄 --> CIPhotoEffectChrome

// CILinearToSRGBToneCurve, CISRGBToneCurveToLinear, CIGaussianBlur, CIBoxBlur, CIDiscBlur, CISepiaTone, CIDepthOfField

+ (UIImage *)filterWithOriginalImage:(UIImage *)image filterName:(NSString *)name{

    CIContext *context = [CIContext contextWithOptions:nil];

    CIImage *inputImage = [[CIImage alloc] initWithImage:image];

    CIFilter *filter = [CIFilter filterWithName:name];

    [filter setValue:inputImage forKey:kCIInputImageKey];

    CIImage *result = [filter valueForKey:kCIOutputImageKey];

    CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];

    UIImage *resultImage = [UIImage imageWithCGImage:cgImage];

    CGImageRelease(cgImage);

    return resultImage;

}





13. 对图片进行模糊处理

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

#pragma mark - 对图片进行模糊处理

// CIGaussianBlur ---> 高斯模糊

// CIBoxBlur      ---> 均值模糊(Available in iOS 9.0 and later)

// CIDiscBlur     ---> 环形卷积模糊(Available in iOS 9.0 and later)

// CIMedianFilter ---> 中值模糊, 用于消除图像噪点, 无需设置radius(Available in iOS 9.0 and later)

// CIMotionBlur   ---> 运动模糊, 用于模拟相机移动拍摄时的扫尾效果(Available in iOS 9.0 and later)

+ (UIImage *)blurWithOriginalImage:(UIImage *)image blurName:(NSString *)name radius:(NSInteger)radius{

    CIContext *context = [CIContext contextWithOptions:nil];

    CIImage *inputImage = [[CIImage alloc] initWithImage:image];

    CIFilter *filter;

    if (name.length != 0) {

        filter = [CIFilter filterWithName:name];

        [filter setValue:inputImage forKey:kCIInputImageKey];

        if (![name isEqualToString:@"CIMedianFilter"]) {

            [filter setValue:@(radius) forKey:@"inputRadius"];

        }

        CIImage *result = [filter valueForKey:kCIOutputImageKey];

        CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];

        UIImage *resultImage = [UIImage imageWithCGImage:cgImage];

        CGImageRelease(cgImage);

        return resultImage;

    }else{

        return nil;

    }

}






14. 调整图片饱和度、亮度、对比度

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

/**

 *  调整图片饱和度, 亮度, 对比度

 *

 *  @param image      目标图片

 *  @param saturation 饱和度

 *  @param brightness 亮度: -1.0 ~ 1.0

 *  @param contrast   对比度

 *

 */

+ (UIImage *)colorControlsWithOriginalImage:(UIImage *)image

                                 saturation:(CGFloat)saturation

                                 brightness:(CGFloat)brightness

                                   contrast:(CGFloat)contrast{

    CIContext *context = [CIContext contextWithOptions:nil];

    CIImage *inputImage = [[CIImage alloc] initWithImage:image];

    CIFilter *filter = [CIFilter filterWithName:@"CIColorControls"];

    [filter setValue:inputImage forKey:kCIInputImageKey];

 

    [filter setValue:@(saturation) forKey:@"inputSaturation"];

    [filter setValue:@(brightness) forKey:@"inputBrightness"];// 0.0 ~ 1.0

    [filter setValue:@(contrast) forKey:@"inputContrast"];

 

    CIImage *result = [filter valueForKey:kCIOutputImageKey];

    CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];

    UIImage *resultImage = [UIImage imageWithCGImage:cgImage];

    CGImageRelease(cgImage);

    return resultImage;

}






15. 创建一张实时模糊效果 View (毛玻璃效果)

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

//Avilable in iOS 8.0 and later

+ (UIVisualEffectView *)effectViewWithFrame:(CGRect)frame{

    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];

    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];

    effectView.frame = frame;

    return effectView;

}





16. 全屏截图

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

8

9

//全屏截图

+ (UIImage *)shotScreen{

    UIWindow *window = [UIApplication sharedApplication].keyWindow;

    UIGraphicsBeginImageContext(window.bounds.size);

    [window.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;

}







17. 截取一张 view 生成图片

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

8

//截取view生成一张图片

+ (UIImage *)shotWithView:(UIView *)view{

    UIGraphicsBeginImageContext(view.bounds.size);

    [view.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;

}






18. 截取view中某个区域生成一张图片

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

//截取view中某个区域生成一张图片

+ (UIImage *)shotWithView:(UIView *)view scope:(CGRect)scope{

    CGImageRef imageRef = CGImageCreateWithImageInRect([self shotWithView:view].CGImage, scope);

    UIGraphicsBeginImageContext(scope.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGRect rect = CGRectMake(0, 0, scope.size.width, scope.size.height);

    CGContextTranslateCTM(context, 0, rect.size.height);//下移

    CGContextScaleCTM(context, 1.0f, -1.0f);//上翻

    CGContextDrawImage(context, rect, imageRef);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    CGImageRelease(imageRef);

    CGContextRelease(context);

    return image;

}







19. 压缩图片到指定尺寸大小

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

8

//压缩图片到指定尺寸大小

+ (UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size{

    UIImage *resultImage = image;

    UIGraphicsBeginImageContext(size);

    [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];

    UIGraphicsEndImageContext();

    return resultImage;

}








20. 压缩图片到指定文件大小

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

//压缩图片到指定文件大小

+ (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size{

    NSData *data = UIImageJPEGRepresentation(image, 1.0);

    CGFloat dataKBytes = data.length/1000.0;

    CGFloat maxQuality = 0.9f;

    CGFloat lastData = dataKBytes;

    while (dataKBytes > size && maxQuality > 0.01f) {

        maxQuality = maxQuality - 0.01f;

        data = UIImageJPEGRepresentation(image, maxQuality);

        dataKBytes = data.length/1000.0;

        if (lastData == dataKBytes) {

            break;

        }else{

            lastData = dataKBytes;

        }

    }

    return data;

}





21. 获取设备 IP 地址

需要先引入下头文件:

[Objective-C] 查看源文件 复制代码

?

1

2

#import <ifaddrs.h>

#import <arpa/inet.h>

 

代码:

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

//获取设备 IP 地址

+ (NSString *)getIPAddress {

    NSString *address = @"error";

    struct ifaddrs *interfaces = NULL;

    struct ifaddrs *temp_addr = NULL;

    int success = 0;

    success = getifaddrs(&interfaces);

    if (success == 0) {

        temp_addr = interfaces;

        while(temp_addr != NULL) {

            if(temp_addr->ifa_addr->sa_family == AF_INET) {

                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {

                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];

                }

            }

            temp_addr = temp_addr->ifa_next;

        }

    }

    freeifaddrs(interfaces);

    return address;

}




22. 判断字符串中是否含有空格

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

8

+ (BOOL)isHaveSpaceInString:(NSString *)string{

    NSRange _range = [string rangeOfString:@" "];

    if (_range.location != NSNotFound) {

        return YES;

    }else {

        return NO;

    }

}






23. 判断字符串中是否含有某个字符串

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

8

+ (BOOL)isHaveString:(NSString *)string1 InString:(NSString *)string2{

    NSRange _range = [string2 rangeOfString:string1];

    if (_range.location != NSNotFound) {

        return YES;

    }else {

        return NO;

    }

}







24. 判断字符串中是否含有中文

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

8

9

+ (BOOL)isHaveChineseInString:(NSString *)string{

    for(NSInteger i = 0; i < [string length]; i++){

        int a = [string characterAtIndex:i];

        if (a > 0x4e00 && a < 0x9fff) {

            return YES;

        }

    }

    return NO;

}





25. 判断字符串是否全部为数字

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

+ (BOOL)isAllNum:(NSString *)string{

    unichar c;

    for (int i=0; i<string.length; i++) {

        c=[string characterAtIndex:i];

        if (!isdigit(c)) {

            return NO;

        }

    }

    return YES;

}





26. 绘制虚线

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

/*

  ** lineFrame:     虚线的 frame

  ** length:        虚线中短线的宽度

  ** spacing:       虚线中短线之间的间距

  ** color:         虚线中短线的颜色

*/

+ (UIView *)createDashedLineWithFrame:(CGRect)lineFrame

                           lineLength:(int)length

                          lineSpacing:(int)spacing

                            lineColor:(UIColor *)color{

    UIView *dashedLine = [[UIView alloc] initWithFrame:lineFrame];

    dashedLine.backgroundColor = [UIColor clearColor];

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];

    [shapeLayer setBounds:dashedLine.bounds];

    [shapeLayer setPosition:CGPointMake(CGRectGetWidth(dashedLine.frame) / 2, CGRectGetHeight(dashedLine.frame))];

    [shapeLayer setFillColor:[UIColor clearColor].CGColor];

    [shapeLayer setStrokeColor:color.CGColor];

    [shapeLayer setLineWidth:CGRectGetHeight(dashedLine.frame)];

    [shapeLayer setLineJoin:kCALineJoinRound];

    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:length], [NSNumber numberWithInt:spacing], nil]];

    CGMutablePathRef path = CGPathCreateMutable();

    CGPathMoveToPoint(path, NULL, 0, 0);

    CGPathAddLineToPoint(path, NULL, CGRectGetWidth(dashedLine.frame), 0);

    [shapeLayer setPath:path];

    CGPathRelease(path);

    [dashedLine.layer addSublayer:shapeLayer];

    return dashedLine;

}

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

//磁盘总空间

+ (CGFloat)diskOfAllSizeMBytes{

    CGFloat size = 0.0;

    NSError *error;

    NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];

    if (error) {

#ifdef DEBUG

        NSLog(@"error: %@", error.localizedDescription);

#endif

    }else{

        NSNumber *number = [dic objectForKey:NSFileSystemSize];

        size = [number floatValue]/1024/1024;

    }

    return size;

}




2. 获取磁盘可用空间大小

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

//磁盘可用空间

+ (CGFloat)diskOfFreeSizeMBytes{

    CGFloat size = 0.0;

    NSError *error;

    NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];

    if (error) {

#ifdef DEBUG

        NSLog(@"error: %@", error.localizedDescription);

#endif

    }else{

        NSNumber *number = [dic objectForKey:NSFileSystemFreeSize];

        size = [number floatValue]/1024/1024;

    }

    return size;

}





3. 获取指定路径下某个文件的大小

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

//获取文件大小

+ (long long)fileSizeAtPath:(NSString *)filePath{

    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath:filePath]) return 0;

    return [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];

}





4. 获取文件夹下所有文件的大小

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

//获取文件夹下所有文件的大小

+ (long long)folderSizeAtPath:(NSString *)folderPath{

    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath:folderPath]) return 0;

    NSEnumerator *filesEnumerator = [[fileManager subpathsAtPath:folderPath] objectEnumerator];

    NSString *fileName;

    long long folerSize = 0;

    while ((fileName = [filesEnumerator nextObject]) != nil) {

        NSString *filePath = [folderPath stringByAppendingPathComponent:fileName];

        folerSize += [self fileSizeAtPath:filePath];

    }

    return folerSize;

}




5. 获取字符串(或汉字)首字母

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

8

//获取字符串(或汉字)首字母

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

    NSMutableString *str = [NSMutableString stringWithString:string];

    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);

    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);

    NSString *pingyin = [str capitalizedString];

    return [pingyin substringToIndex:1];

}







6. 将字符串数组按照元素首字母顺序进行排序分组

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

//将字符串数组按照元素首字母顺序进行排序分组

+ (NSDictionary *)dictionaryOrderByCharacterWithOriginalArray:(NSArray *)array{

    if (array.count == 0) {

        return nil;

    }

    for (id obj in array) {

        if (![obj isKindOfClass:[NSString class]]) {

            return nil;

        }

    }

    UILocalizedIndexedCollation *indexedCollation = [UILocalizedIndexedCollation currentCollation];

    NSMutableArray *objects = [NSMutableArray arrayWithCapacity:indexedCollation.sectionTitles.count];

    //创建27个分组数组

    for (int i = 0; i < indexedCollation.sectionTitles.count; i++) {

        NSMutableArray *obj = [NSMutableArray array];

        [objects addObject:obj];

    }

    NSMutableArray *keys = [NSMutableArray arrayWithCapacity:objects.count];

    //按字母顺序进行分组

    NSInteger lastIndex = -1;

    for (int i = 0; i < array.count; i++) {

        NSInteger index = [indexedCollation sectionForObject:array[i] collationStringSelector:@selector(uppercaseString)];

        [[objects objectAtIndex:index] addObject:array[i]];

        lastIndex = index;

    }

    //去掉空数组

    for (int i = 0; i < objects.count; i++) {

        NSMutableArray *obj = objects[i];

        if (obj.count == 0) {

            [objects removeObject:obj];

        }

    }

    //获取索引字母

    for (NSMutableArray *obj in objects) {

        NSString *str = obj[0];

        NSString *key = [self firstCharacterWithString:str];

        [keys addObject:key];

    }

    NSMutableDictionary *dic = [NSMutableDictionary dictionary];

    [dic setObject:objects forKey:keys];

    return dic;

}

 

//获取字符串(或汉字)首字母

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

    NSMutableString *str = [NSMutableString stringWithString:string];

    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);

    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);

    NSString *pingyin = [str capitalizedString];

    return [pingyin substringToIndex:1];

}

使用如下:

[Objective-C] 查看源文件 复制代码

?

1

2

3

NSArray *arr = @[@"guangzhou", @"shanghai", @"北京", @"henan", @"hainan"];

NSDictionary *dic = [Utilities dictionaryOrderByCharacterWithOriginalArray:arr];

NSLog(@"\n\ndic: %@", dic);


输出结果如下:

 
输出结果


7. 获取当前时间

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

//获取当前时间

//format: @"yyyy-MM-dd HH:mm:ss"、@"yyyy年MM月dd日 HH时mm分ss秒"

+ (NSString *)currentDateWithFormat:(NSString *)format{

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

    [dateFormatter setDateFormat:format];

    return [dateFormatter stringFromDate:[NSDate date]];

}






8. 计算上次日期距离现在多久, 如 xx 小时前、xx 分钟前等

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

/**

 *  计算上次日期距离现在多久

 *

 *  @param lastTime    上次日期(需要和格式对应)

 *  @param format1     上次日期格式

 *  @param currentTime 最近日期(需要和格式对应)

 *  @param format2     最近日期格式

 *

 *  @return xx分钟前、xx小时前、xx天前

 */

+ (NSString *)timeIntervalFromLastTime:(NSString *)lastTime

                        lastTimeFormat:(NSString *)format1

                         ToCurrentTime:(NSString *)currentTime

                     currentTimeFormat:(NSString *)format2{

    //上次时间

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

    dateFormatter1.dateFormat = format1;

    NSDate *lastDate = [dateFormatter1 dateFromString:lastTime];

    //当前时间

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

    dateFormatter2.dateFormat = format2;

    NSDate *currentDate = [dateFormatter2 dateFromString:currentTime];

    return [Utilities timeIntervalFromLastTime:lastDate ToCurrentTime:currentDate];

}

 

+ (NSString *)timeIntervalFromLastTime:(NSDate *)lastTime ToCurrentTime:(NSDate *)currentTime{

    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];

    //上次时间

    NSDate *lastDate = [lastTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:lastTime]];

    //当前时间

    NSDate *currentDate = [currentTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:currentTime]];

    //时间间隔

    NSInteger intevalTime = [currentDate timeIntervalSinceReferenceDate] - [lastDate timeIntervalSinceReferenceDate];

 

    //秒、分、小时、天、月、年

    NSInteger minutes = intevalTime / 60;

    NSInteger hours = intevalTime / 60 / 60;

    NSInteger day = intevalTime / 60 / 60 / 24;

    NSInteger month = intevalTime / 60 / 60 / 24 / 30;

    NSInteger yers = intevalTime / 60 / 60 / 24 / 365;

 

    if (minutes <= 10) {

        return  @"刚刚";

    }else if (minutes < 60){

        return [NSString stringWithFormat: @"%ld分钟前",(long)minutes];

    }else if (hours < 24){

        return [NSString stringWithFormat: @"%ld小时前",(long)hours];

    }else if (day < 30){

        return [NSString stringWithFormat: @"%ld天前",(long)day];

    }else if (month < 12){

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

        df.dateFormat = @"M月d日";

        NSString * time = [df stringFromDate:lastDate];

        return time;

    }else if (yers >= 1){

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

        df.dateFormat = @"yyyy年M月d日";

        NSString * time = [df stringFromDate:lastDate];

        return time;

    }

    return @"";

}



 

使用如下:

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

NSLog(@"\n\nresult: %@", [Utilities timeIntervalFromLastTime:@"2015年12月8日 15:50"

                                           lastTimeFormat:@"yyyy年MM月dd日 HH:mm"

                                            ToCurrentTime:@"2015/12/08 16:12"

                                        currentTimeFormat:@"yyyy/MM/dd HH:mm"]);






 

输出结果如下:

 
输出结果


9. 判断手机号码格式是否正确

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

//判断手机号码格式是否正确

+ (BOOL)valiMobile:(NSString *)mobile{

    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];

    if (mobile.length != 11)

    {

        return NO;

    }else{

        /**

         * 移动号段正则表达式

         */

        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";

        /**

         * 联通号段正则表达式

         */

        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";

        /**

         * 电信号段正则表达式

         */

        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";

        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];

        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];

        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];

        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];

        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];

        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];

 

        if (isMatch1 || isMatch2 || isMatch3) {

            return YES;

        }else{

            return NO;

        }

    }

}






10. 判断邮箱格式是否正确

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

//利用正则表达式验证

+ (BOOL)isAvailableEmail:(NSString *)email {

    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";

    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];

    return [emailTest evaluateWithObject:email];

}





11. 将十六进制颜色转换为 UIColor 对象

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

//将十六进制颜色转换为 UIColor 对象

+ (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];

}





12. 对图片进行滤镜处理

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

#pragma mark - 对图片进行滤镜处理

// 怀旧 --> CIPhotoEffectInstant                         单色 --> CIPhotoEffectMono

// 黑白 --> CIPhotoEffectNoir                            褪色 --> CIPhotoEffectFade

// 色调 --> CIPhotoEffectTonal                           冲印 --> CIPhotoEffectProcess

// 岁月 --> CIPhotoEffectTransfer                        铬黄 --> CIPhotoEffectChrome

// CILinearToSRGBToneCurve, CISRGBToneCurveToLinear, CIGaussianBlur, CIBoxBlur, CIDiscBlur, CISepiaTone, CIDepthOfField

+ (UIImage *)filterWithOriginalImage:(UIImage *)image filterName:(NSString *)name{

    CIContext *context = [CIContext contextWithOptions:nil];

    CIImage *inputImage = [[CIImage alloc] initWithImage:image];

    CIFilter *filter = [CIFilter filterWithName:name];

    [filter setValue:inputImage forKey:kCIInputImageKey];

    CIImage *result = [filter valueForKey:kCIOutputImageKey];

    CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];

    UIImage *resultImage = [UIImage imageWithCGImage:cgImage];

    CGImageRelease(cgImage);

    return resultImage;

}





13. 对图片进行模糊处理

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

#pragma mark - 对图片进行模糊处理

// CIGaussianBlur ---> 高斯模糊

// CIBoxBlur      ---> 均值模糊(Available in iOS 9.0 and later)

// CIDiscBlur     ---> 环形卷积模糊(Available in iOS 9.0 and later)

// CIMedianFilter ---> 中值模糊, 用于消除图像噪点, 无需设置radius(Available in iOS 9.0 and later)

// CIMotionBlur   ---> 运动模糊, 用于模拟相机移动拍摄时的扫尾效果(Available in iOS 9.0 and later)

+ (UIImage *)blurWithOriginalImage:(UIImage *)image blurName:(NSString *)name radius:(NSInteger)radius{

    CIContext *context = [CIContext contextWithOptions:nil];

    CIImage *inputImage = [[CIImage alloc] initWithImage:image];

    CIFilter *filter;

    if (name.length != 0) {

        filter = [CIFilter filterWithName:name];

        [filter setValue:inputImage forKey:kCIInputImageKey];

        if (![name isEqualToString:@"CIMedianFilter"]) {

            [filter setValue:@(radius) forKey:@"inputRadius"];

        }

        CIImage *result = [filter valueForKey:kCIOutputImageKey];

        CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];

        UIImage *resultImage = [UIImage imageWithCGImage:cgImage];

        CGImageRelease(cgImage);

        return resultImage;

    }else{

        return nil;

    }

}






14. 调整图片饱和度、亮度、对比度

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

/**

 *  调整图片饱和度, 亮度, 对比度

 *

 *  @param image      目标图片

 *  @param saturation 饱和度

 *  @param brightness 亮度: -1.0 ~ 1.0

 *  @param contrast   对比度

 *

 */

+ (UIImage *)colorControlsWithOriginalImage:(UIImage *)image

                                 saturation:(CGFloat)saturation

                                 brightness:(CGFloat)brightness

                                   contrast:(CGFloat)contrast{

    CIContext *context = [CIContext contextWithOptions:nil];

    CIImage *inputImage = [[CIImage alloc] initWithImage:image];

    CIFilter *filter = [CIFilter filterWithName:@"CIColorControls"];

    [filter setValue:inputImage forKey:kCIInputImageKey];

 

    [filter setValue:@(saturation) forKey:@"inputSaturation"];

    [filter setValue:@(brightness) forKey:@"inputBrightness"];// 0.0 ~ 1.0

    [filter setValue:@(contrast) forKey:@"inputContrast"];

 

    CIImage *result = [filter valueForKey:kCIOutputImageKey];

    CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];

    UIImage *resultImage = [UIImage imageWithCGImage:cgImage];

    CGImageRelease(cgImage);

    return resultImage;

}






15. 创建一张实时模糊效果 View (毛玻璃效果)

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

//Avilable in iOS 8.0 and later

+ (UIVisualEffectView *)effectViewWithFrame:(CGRect)frame{

    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];

    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];

    effectView.frame = frame;

    return effectView;

}





16. 全屏截图

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

8

9

//全屏截图

+ (UIImage *)shotScreen{

    UIWindow *window = [UIApplication sharedApplication].keyWindow;

    UIGraphicsBeginImageContext(window.bounds.size);

    [window.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;

}







17. 截取一张 view 生成图片

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

8

//截取view生成一张图片

+ (UIImage *)shotWithView:(UIView *)view{

    UIGraphicsBeginImageContext(view.bounds.size);

    [view.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;

}






18. 截取view中某个区域生成一张图片

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

//截取view中某个区域生成一张图片

+ (UIImage *)shotWithView:(UIView *)view scope:(CGRect)scope{

    CGImageRef imageRef = CGImageCreateWithImageInRect([self shotWithView:view].CGImage, scope);

    UIGraphicsBeginImageContext(scope.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGRect rect = CGRectMake(0, 0, scope.size.width, scope.size.height);

    CGContextTranslateCTM(context, 0, rect.size.height);//下移

    CGContextScaleCTM(context, 1.0f, -1.0f);//上翻

    CGContextDrawImage(context, rect, imageRef);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    CGImageRelease(imageRef);

    CGContextRelease(context);

    return image;

}







19. 压缩图片到指定尺寸大小

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

8

//压缩图片到指定尺寸大小

+ (UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size{

    UIImage *resultImage = image;

    UIGraphicsBeginImageContext(size);

    [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];

    UIGraphicsEndImageContext();

    return resultImage;

}








20. 压缩图片到指定文件大小

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

//压缩图片到指定文件大小

+ (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size{

    NSData *data = UIImageJPEGRepresentation(image, 1.0);

    CGFloat dataKBytes = data.length/1000.0;

    CGFloat maxQuality = 0.9f;

    CGFloat lastData = dataKBytes;

    while (dataKBytes > size && maxQuality > 0.01f) {

        maxQuality = maxQuality - 0.01f;

        data = UIImageJPEGRepresentation(image, maxQuality);

        dataKBytes = data.length/1000.0;

        if (lastData == dataKBytes) {

            break;

        }else{

            lastData = dataKBytes;

        }

    }

    return data;

}





21. 获取设备 IP 地址

需要先引入下头文件:

[Objective-C] 查看源文件 复制代码

?

1

2

#import <ifaddrs.h>

#import <arpa/inet.h>

 

代码:

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

//获取设备 IP 地址

+ (NSString *)getIPAddress {

    NSString *address = @"error";

    struct ifaddrs *interfaces = NULL;

    struct ifaddrs *temp_addr = NULL;

    int success = 0;

    success = getifaddrs(&interfaces);

    if (success == 0) {

        temp_addr = interfaces;

        while(temp_addr != NULL) {

            if(temp_addr->ifa_addr->sa_family == AF_INET) {

                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {

                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];

                }

            }

            temp_addr = temp_addr->ifa_next;

        }

    }

    freeifaddrs(interfaces);

    return address;

}




22. 判断字符串中是否含有空格

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

8

+ (BOOL)isHaveSpaceInString:(NSString *)string{

    NSRange _range = [string rangeOfString:@" "];

    if (_range.location != NSNotFound) {

        return YES;

    }else {

        return NO;

    }

}






23. 判断字符串中是否含有某个字符串

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

8

+ (BOOL)isHaveString:(NSString *)string1 InString:(NSString *)string2{

    NSRange _range = [string2 rangeOfString:string1];

    if (_range.location != NSNotFound) {

        return YES;

    }else {

        return NO;

    }

}







24. 判断字符串中是否含有中文

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

8

9

+ (BOOL)isHaveChineseInString:(NSString *)string{

    for(NSInteger i = 0; i < [string length]; i++){

        int a = [string characterAtIndex:i];

        if (a > 0x4e00 && a < 0x9fff) {

            return YES;

        }

    }

    return NO;

}





25. 判断字符串是否全部为数字

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

+ (BOOL)isAllNum:(NSString *)string{

    unichar c;

    for (int i=0; i<string.length; i++) {

        c=[string characterAtIndex:i];

        if (!isdigit(c)) {

            return NO;

        }

    }

    return YES;

}





26. 绘制虚线

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

/*

  ** lineFrame:     虚线的 frame

  ** length:        虚线中短线的宽度

  ** spacing:       虚线中短线之间的间距

  ** color:         虚线中短线的颜色

*/

+ (UIView *)createDashedLineWithFrame:(CGRect)lineFrame

                           lineLength:(int)length

                          lineSpacing:(int)spacing

                            lineColor:(UIColor *)color{

    UIView *dashedLine = [[UIView alloc] initWithFrame:lineFrame];

    dashedLine.backgroundColor = [UIColor clearColor];

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];

    [shapeLayer setBounds:dashedLine.bounds];

    [shapeLayer setPosition:CGPointMake(CGRectGetWidth(dashedLine.frame) / 2, CGRectGetHeight(dashedLine.frame))];

    [shapeLayer setFillColor:[UIColor clearColor].CGColor];

    [shapeLayer setStrokeColor:color.CGColor];

    [shapeLayer setLineWidth:CGRectGetHeight(dashedLine.frame)];

    [shapeLayer setLineJoin:kCALineJoinRound];

    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:length], [NSNumber numberWithInt:spacing], nil]];

    CGMutablePathRef path = CGPathCreateMutable();

    CGPathMoveToPoint(path, NULL, 0, 0);

    CGPathAddLineToPoint(path, NULL, CGRectGetWidth(dashedLine.frame), 0);

    [shapeLayer setPath:path];

    CGPathRelease(path);

    [dashedLine.layer addSublayer:shapeLayer];

    return dashedLine;

}

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

//磁盘总空间

+ (CGFloat)diskOfAllSizeMBytes{

    CGFloat size = 0.0;

    NSError *error;

    NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];

    if (error) {

#ifdef DEBUG

        NSLog(@"error: %@", error.localizedDescription);

#endif

    }else{

        NSNumber *number = [dic objectForKey:NSFileSystemSize];

        size = [number floatValue]/1024/1024;

    }

    return size;

}




2. 获取磁盘可用空间大小

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

//磁盘可用空间

+ (CGFloat)diskOfFreeSizeMBytes{

    CGFloat size = 0.0;

    NSError *error;

    NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];

    if (error) {

#ifdef DEBUG

        NSLog(@"error: %@", error.localizedDescription);

#endif

    }else{

        NSNumber *number = [dic objectForKey:NSFileSystemFreeSize];

        size = [number floatValue]/1024/1024;

    }

    return size;

}





3. 获取指定路径下某个文件的大小

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

//获取文件大小

+ (long long)fileSizeAtPath:(NSString *)filePath{

    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath:filePath]) return 0;

    return [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];

}





4. 获取文件夹下所有文件的大小

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

//获取文件夹下所有文件的大小

+ (long long)folderSizeAtPath:(NSString *)folderPath{

    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath:folderPath]) return 0;

    NSEnumerator *filesEnumerator = [[fileManager subpathsAtPath:folderPath] objectEnumerator];

    NSString *fileName;

    long long folerSize = 0;

    while ((fileName = [filesEnumerator nextObject]) != nil) {

        NSString *filePath = [folderPath stringByAppendingPathComponent:fileName];

        folerSize += [self fileSizeAtPath:filePath];

    }

    return folerSize;

}




5. 获取字符串(或汉字)首字母

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

8

//获取字符串(或汉字)首字母

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

    NSMutableString *str = [NSMutableString stringWithString:string];

    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);

    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);

    NSString *pingyin = [str capitalizedString];

    return [pingyin substringToIndex:1];

}







6. 将字符串数组按照元素首字母顺序进行排序分组

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

//将字符串数组按照元素首字母顺序进行排序分组

+ (NSDictionary *)dictionaryOrderByCharacterWithOriginalArray:(NSArray *)array{

    if (array.count == 0) {

        return nil;

    }

    for (id obj in array) {

        if (![obj isKindOfClass:[NSString class]]) {

            return nil;

        }

    }

    UILocalizedIndexedCollation *indexedCollation = [UILocalizedIndexedCollation currentCollation];

    NSMutableArray *objects = [NSMutableArray arrayWithCapacity:indexedCollation.sectionTitles.count];

    //创建27个分组数组

    for (int i = 0; i < indexedCollation.sectionTitles.count; i++) {

        NSMutableArray *obj = [NSMutableArray array];

        [objects addObject:obj];

    }

    NSMutableArray *keys = [NSMutableArray arrayWithCapacity:objects.count];

    //按字母顺序进行分组

    NSInteger lastIndex = -1;

    for (int i = 0; i < array.count; i++) {

        NSInteger index = [indexedCollation sectionForObject:array[i] collationStringSelector:@selector(uppercaseString)];

        [[objects objectAtIndex:index] addObject:array[i]];

        lastIndex = index;

    }

    //去掉空数组

    for (int i = 0; i < objects.count; i++) {

        NSMutableArray *obj = objects[i];

        if (obj.count == 0) {

            [objects removeObject:obj];

        }

    }

    //获取索引字母

    for (NSMutableArray *obj in objects) {

        NSString *str = obj[0];

        NSString *key = [self firstCharacterWithString:str];

        [keys addObject:key];

    }

    NSMutableDictionary *dic = [NSMutableDictionary dictionary];

    [dic setObject:objects forKey:keys];

    return dic;

}

 

//获取字符串(或汉字)首字母

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

    NSMutableString *str = [NSMutableString stringWithString:string];

    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);

    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);

    NSString *pingyin = [str capitalizedString];

    return [pingyin substringToIndex:1];

}

使用如下:

[Objective-C] 查看源文件 复制代码

?

1

2

3

NSArray *arr = @[@"guangzhou", @"shanghai", @"北京", @"henan", @"hainan"];

NSDictionary *dic = [Utilities dictionaryOrderByCharacterWithOriginalArray:arr];

NSLog(@"\n\ndic: %@", dic);


输出结果如下:

 
输出结果


7. 获取当前时间

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

//获取当前时间

//format: @"yyyy-MM-dd HH:mm:ss"、@"yyyy年MM月dd日 HH时mm分ss秒"

+ (NSString *)currentDateWithFormat:(NSString *)format{

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

    [dateFormatter setDateFormat:format];

    return [dateFormatter stringFromDate:[NSDate date]];

}






8. 计算上次日期距离现在多久, 如 xx 小时前、xx 分钟前等

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

/**

 *  计算上次日期距离现在多久

 *

 *  @param lastTime    上次日期(需要和格式对应)

 *  @param format1     上次日期格式

 *  @param currentTime 最近日期(需要和格式对应)

 *  @param format2     最近日期格式

 *

 *  @return xx分钟前、xx小时前、xx天前

 */

+ (NSString *)timeIntervalFromLastTime:(NSString *)lastTime

                        lastTimeFormat:(NSString *)format1

                         ToCurrentTime:(NSString *)currentTime

                     currentTimeFormat:(NSString *)format2{

    //上次时间

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

    dateFormatter1.dateFormat = format1;

    NSDate *lastDate = [dateFormatter1 dateFromString:lastTime];

    //当前时间

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

    dateFormatter2.dateFormat = format2;

    NSDate *currentDate = [dateFormatter2 dateFromString:currentTime];

    return [Utilities timeIntervalFromLastTime:lastDate ToCurrentTime:currentDate];

}

 

+ (NSString *)timeIntervalFromLastTime:(NSDate *)lastTime ToCurrentTime:(NSDate *)currentTime{

    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];

    //上次时间

    NSDate *lastDate = [lastTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:lastTime]];

    //当前时间

    NSDate *currentDate = [currentTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:currentTime]];

    //时间间隔

    NSInteger intevalTime = [currentDate timeIntervalSinceReferenceDate] - [lastDate timeIntervalSinceReferenceDate];

 

    //秒、分、小时、天、月、年

    NSInteger minutes = intevalTime / 60;

    NSInteger hours = intevalTime / 60 / 60;

    NSInteger day = intevalTime / 60 / 60 / 24;

    NSInteger month = intevalTime / 60 / 60 / 24 / 30;

    NSInteger yers = intevalTime / 60 / 60 / 24 / 365;

 

    if (minutes <= 10) {

        return  @"刚刚";

    }else if (minutes < 60){

        return [NSString stringWithFormat: @"%ld分钟前",(long)minutes];

    }else if (hours < 24){

        return [NSString stringWithFormat: @"%ld小时前",(long)hours];

    }else if (day < 30){

        return [NSString stringWithFormat: @"%ld天前",(long)day];

    }else if (month < 12){

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

        df.dateFormat = @"M月d日";

        NSString * time = [df stringFromDate:lastDate];

        return time;

    }else if (yers >= 1){

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

        df.dateFormat = @"yyyy年M月d日";

        NSString * time = [df stringFromDate:lastDate];

        return time;

    }

    return @"";

}



 

使用如下:

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

NSLog(@"\n\nresult: %@", [Utilities timeIntervalFromLastTime:@"2015年12月8日 15:50"

                                           lastTimeFormat:@"yyyy年MM月dd日 HH:mm"

                                            ToCurrentTime:@"2015/12/08 16:12"

                                        currentTimeFormat:@"yyyy/MM/dd HH:mm"]);






 

输出结果如下:

 
输出结果


9. 判断手机号码格式是否正确

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

//判断手机号码格式是否正确

+ (BOOL)valiMobile:(NSString *)mobile{

    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];

    if (mobile.length != 11)

    {

        return NO;

    }else{

        /**

         * 移动号段正则表达式

         */

        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";

        /**

         * 联通号段正则表达式

         */

        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";

        /**

         * 电信号段正则表达式

         */

        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";

        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];

        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];

        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];

        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];

        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];

        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];

 

        if (isMatch1 || isMatch2 || isMatch3) {

            return YES;

        }else{

            return NO;

        }

    }

}






10. 判断邮箱格式是否正确

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

//利用正则表达式验证

+ (BOOL)isAvailableEmail:(NSString *)email {

    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";

    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];

    return [emailTest evaluateWithObject:email];

}





11. 将十六进制颜色转换为 UIColor 对象

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

//将十六进制颜色转换为 UIColor 对象

+ (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];

}





12. 对图片进行滤镜处理

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

#pragma mark - 对图片进行滤镜处理

// 怀旧 --> CIPhotoEffectInstant                         单色 --> CIPhotoEffectMono

// 黑白 --> CIPhotoEffectNoir                            褪色 --> CIPhotoEffectFade

// 色调 --> CIPhotoEffectTonal                           冲印 --> CIPhotoEffectProcess

// 岁月 --> CIPhotoEffectTransfer                        铬黄 --> CIPhotoEffectChrome

// CILinearToSRGBToneCurve, CISRGBToneCurveToLinear, CIGaussianBlur, CIBoxBlur, CIDiscBlur, CISepiaTone, CIDepthOfField

+ (UIImage *)filterWithOriginalImage:(UIImage *)image filterName:(NSString *)name{

    CIContext *context = [CIContext contextWithOptions:nil];

    CIImage *inputImage = [[CIImage alloc] initWithImage:image];

    CIFilter *filter = [CIFilter filterWithName:name];

    [filter setValue:inputImage forKey:kCIInputImageKey];

    CIImage *result = [filter valueForKey:kCIOutputImageKey];

    CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];

    UIImage *resultImage = [UIImage imageWithCGImage:cgImage];

    CGImageRelease(cgImage);

    return resultImage;

}





13. 对图片进行模糊处理

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

#pragma mark - 对图片进行模糊处理

// CIGaussianBlur ---> 高斯模糊

// CIBoxBlur      ---> 均值模糊(Available in iOS 9.0 and later)

// CIDiscBlur     ---> 环形卷积模糊(Available in iOS 9.0 and later)

// CIMedianFilter ---> 中值模糊, 用于消除图像噪点, 无需设置radius(Available in iOS 9.0 and later)

// CIMotionBlur   ---> 运动模糊, 用于模拟相机移动拍摄时的扫尾效果(Available in iOS 9.0 and later)

+ (UIImage *)blurWithOriginalImage:(UIImage *)image blurName:(NSString *)name radius:(NSInteger)radius{

    CIContext *context = [CIContext contextWithOptions:nil];

    CIImage *inputImage = [[CIImage alloc] initWithImage:image];

    CIFilter *filter;

    if (name.length != 0) {

        filter = [CIFilter filterWithName:name];

        [filter setValue:inputImage forKey:kCIInputImageKey];

        if (![name isEqualToString:@"CIMedianFilter"]) {

            [filter setValue:@(radius) forKey:@"inputRadius"];

        }

        CIImage *result = [filter valueForKey:kCIOutputImageKey];

        CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];

        UIImage *resultImage = [UIImage imageWithCGImage:cgImage];

        CGImageRelease(cgImage);

        return resultImage;

    }else{

        return nil;

    }

}






14. 调整图片饱和度、亮度、对比度

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

/**

 *  调整图片饱和度, 亮度, 对比度

 *

 *  @param image      目标图片

 *  @param saturation 饱和度

 *  @param brightness 亮度: -1.0 ~ 1.0

 *  @param contrast   对比度

 *

 */

+ (UIImage *)colorControlsWithOriginalImage:(UIImage *)image

                                 saturation:(CGFloat)saturation

                                 brightness:(CGFloat)brightness

                                   contrast:(CGFloat)contrast{

    CIContext *context = [CIContext contextWithOptions:nil];

    CIImage *inputImage = [[CIImage alloc] initWithImage:image];

    CIFilter *filter = [CIFilter filterWithName:@"CIColorControls"];

    [filter setValue:inputImage forKey:kCIInputImageKey];

 

    [filter setValue:@(saturation) forKey:@"inputSaturation"];

    [filter setValue:@(brightness) forKey:@"inputBrightness"];// 0.0 ~ 1.0

    [filter setValue:@(contrast) forKey:@"inputContrast"];

 

    CIImage *result = [filter valueForKey:kCIOutputImageKey];

    CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];

    UIImage *resultImage = [UIImage imageWithCGImage:cgImage];

    CGImageRelease(cgImage);

    return resultImage;

}






15. 创建一张实时模糊效果 View (毛玻璃效果)

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

//Avilable in iOS 8.0 and later

+ (UIVisualEffectView *)effectViewWithFrame:(CGRect)frame{

    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];

    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];

    effectView.frame = frame;

    return effectView;

}





16. 全屏截图

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

8

9

//全屏截图

+ (UIImage *)shotScreen{

    UIWindow *window = [UIApplication sharedApplication].keyWindow;

    UIGraphicsBeginImageContext(window.bounds.size);

    [window.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;

}







17. 截取一张 view 生成图片

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

8

//截取view生成一张图片

+ (UIImage *)shotWithView:(UIView *)view{

    UIGraphicsBeginImageContext(view.bounds.size);

    [view.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;

}






18. 截取view中某个区域生成一张图片

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

//截取view中某个区域生成一张图片

+ (UIImage *)shotWithView:(UIView *)view scope:(CGRect)scope{

    CGImageRef imageRef = CGImageCreateWithImageInRect([self shotWithView:view].CGImage, scope);

    UIGraphicsBeginImageContext(scope.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGRect rect = CGRectMake(0, 0, scope.size.width, scope.size.height);

    CGContextTranslateCTM(context, 0, rect.size.height);//下移

    CGContextScaleCTM(context, 1.0f, -1.0f);//上翻

    CGContextDrawImage(context, rect, imageRef);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    CGImageRelease(imageRef);

    CGContextRelease(context);

    return image;

}







19. 压缩图片到指定尺寸大小

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

8

//压缩图片到指定尺寸大小

+ (UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size{

    UIImage *resultImage = image;

    UIGraphicsBeginImageContext(size);

    [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];

    UIGraphicsEndImageContext();

    return resultImage;

}








20. 压缩图片到指定文件大小

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

//压缩图片到指定文件大小

+ (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size{

    NSData *data = UIImageJPEGRepresentation(image, 1.0);

    CGFloat dataKBytes = data.length/1000.0;

    CGFloat maxQuality = 0.9f;

    CGFloat lastData = dataKBytes;

    while (dataKBytes > size && maxQuality > 0.01f) {

        maxQuality = maxQuality - 0.01f;

        data = UIImageJPEGRepresentation(image, maxQuality);

        dataKBytes = data.length/1000.0;

        if (lastData == dataKBytes) {

            break;

        }else{

            lastData = dataKBytes;

        }

    }

    return data;

}





21. 获取设备 IP 地址

需要先引入下头文件:

[Objective-C] 查看源文件 复制代码

?

1

2

#import <ifaddrs.h>

#import <arpa/inet.h>

 

代码:

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

//获取设备 IP 地址

+ (NSString *)getIPAddress {

    NSString *address = @"error";

    struct ifaddrs *interfaces = NULL;

    struct ifaddrs *temp_addr = NULL;

    int success = 0;

    success = getifaddrs(&interfaces);

    if (success == 0) {

        temp_addr = interfaces;

        while(temp_addr != NULL) {

            if(temp_addr->ifa_addr->sa_family == AF_INET) {

                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {

                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];

                }

            }

            temp_addr = temp_addr->ifa_next;

        }

    }

    freeifaddrs(interfaces);

    return address;

}




22. 判断字符串中是否含有空格

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

8

+ (BOOL)isHaveSpaceInString:(NSString *)string{

    NSRange _range = [string rangeOfString:@" "];

    if (_range.location != NSNotFound) {

        return YES;

    }else {

        return NO;

    }

}






23. 判断字符串中是否含有某个字符串

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

8

+ (BOOL)isHaveString:(NSString *)string1 InString:(NSString *)string2{

    NSRange _range = [string2 rangeOfString:string1];

    if (_range.location != NSNotFound) {

        return YES;

    }else {

        return NO;

    }

}







24. 判断字符串中是否含有中文

[Objective-C] 查看源文件 复制代码

?

1

2

3

4

5

6

7

8

9

+ (BOOL)isHaveChineseInString:(NSString *)string{

    for(NSInteger i = 0; i < [string length]; i++){

        int a = [string characterAtIndex:i];

        if (a > 0x4e00 && a < 0x9fff) {

            return YES;

        }

    }

    return NO;

}





25. 判断字符串是否全部为数字

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

+ (BOOL)isAllNum:(NSString *)string{

    unichar c;

    for (int i=0; i<string.length; i++) {

        c=[string characterAtIndex:i];

        if (!isdigit(c)) {

            return NO;

        }

    }

    return YES;

}





26. 绘制虚线

[Objective-C] 查看源文件 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

/*

  ** lineFrame:     虚线的 frame

  ** length:        虚线中短线的宽度

  ** spacing:       虚线中短线之间的间距

  ** color:         虚线中短线的颜色

*/

+ (UIView *)createDashedLineWithFrame:(CGRect)lineFrame

                           lineLength:(int)length

                          lineSpacing:(int)spacing

                            lineColor:(UIColor *)color{

    UIView *dashedLine = [[UIView alloc] initWithFrame:lineFrame];

    dashedLine.backgroundColor = [UIColor clearColor];

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];

    [shapeLayer setBounds:dashedLine.bounds];

    [shapeLayer setPosition:CGPointMake(CGRectGetWidth(dashedLine.frame) / 2, CGRectGetHeight(dashedLine.frame))];

    [shapeLayer setFillColor:[UIColor clearColor].CGColor];

    [shapeLayer setStrokeColor:color.CGColor];

    [shapeLayer setLineWidth:CGRectGetHeight(dashedLine.frame)];

    [shapeLayer setLineJoin:kCALineJoinRound];

    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:length], [NSNumber numberWithInt:spacing], nil]];

    CGMutablePathRef path = CGPathCreateMutable();

    CGPathMoveToPoint(path, NULL, 0, 0);

    CGPathAddLineToPoint(path, NULL, CGRectGetWidth(dashedLine.frame), 0);

    [shapeLayer setPath:path];

    CGPathRelease(path);

    [dashedLine.layer addSublayer:shapeLayer];

    return dashedLine;

}

© 著作权归作者所有

共有 人打赏支持
m
粉丝 0
博文 1
码字总数 9245
作品 0
厦门
【AR】开始使用Vuforia开发iOS(2)

原 设置iOS开发环境 安装Vuforia iOS SDK 如何安装Vuforia iOS示例 编译并运行Vuforia iOS示例 支持iOS金属 iOS 64位迁移 设置iOS开发环境 适用于iOS的Vuforia引擎目前支持运行iOS 9及更高版...

lichong951 ⋅ 06/11 ⋅ 0

从Xamarin.Essentials谈Xamarin库的封装

编者语:Xamarin在国内的推广还需要努力,其实这真的是移动端开发的一大福音,毕竟用一份代码的时间可以生成iOS/Android/Windows/Linux/macOS/Tizen多个平台,而且是原生的性能。Xamarin在B...

⋅ 05/10 ⋅ 0

c++ cout 控制精度、宽度、进制

设置以上这些属性均有两种写法 一种是调用cout的方法 暂且叫做方法写法 一种是用到iomanip的函数 叫做控制器写法 一、精度 控制器写法: cout << setprecision(5); cout << fixed; 方法写法:...

apachecn_飞龙 ⋅ 2014/03/06 ⋅ 0

面试官自述:面向高级开发人员的iOS面试问题

当您准备进行技术性iOS面试时,了解您可能会询问哪些主题以及经验丰富的iOS开发人员期望什么是非常重要的。 这是许多硅谷公司用来衡量iOS候选人资历水平的一系列问题。 这些问题涉及iOS开发的...

菇哒微课 ⋅ 04/26 ⋅ 0

Unity与IOS交互,调用IOS系统相机和相册

前面两篇总结了一下unity与android的简单交互和调用安卓系统相机和相册,比较蛋疼的是,后来发现不同的测试机上会有不同的bug。。。下阶段要一个一个的解决一下 今天总结一下与IOS的交互。这...

qq_32587659 ⋅ 05/16 ⋅ 0

Appium 1.8.0 发布,全面支持 W3C WebDriver 规范

Appium 是一个开源、跨平台的自动化测试工具,最初主要用于测试原生和轻量移动应用,包括 iOS 和 Android ,目前还支持对 Windows 平台上的应用的自动化测试。 Appium 1.8.0 发布,引入了对 ...

王练 ⋅ 04/25 ⋅ 0

HDU ~ 6297 ~ CCPC直播 (模拟,输出格式控制)

思路:模拟就行了,注意Running和RTE的开头字母一样。 iomanip是I/O流控制头文件,就像printf的格式化输出一样。 以下是一些常用的: dec 置基数为10 相当于"%d" hex 置基数为16 相当于"%X" oc...

zscdst ⋅ 05/29 ⋅ 0

iOS基础深入补完计划--NSURLSession使用详解(附Demo)

目录 前言 API Demo 前言 本文主要是把NSURLSession以及NSURLSessionTask相关的代理方法全部整理了一下。 旨在大体了解在一个iOS网络请求中、一个任务究竟经理了什么。 而我们、又能做些什么...

kirito_song ⋅ 05/10 ⋅ 0

苹果对体无完肤的 iOS 11 最后的弥补

点击上方“CSDN”,选择“置顶公众号” 关键时刻,第一时间送达! 距离万众瞩目的苹果开发者大会(WWDC 2018)的召开还有不到一周时间,苹果公司于今天凌晨,正式发布了 iOS 11 的第十四次更...

csdnnews ⋅ 05/30 ⋅ 0

开发微信H5视频秀项目遇到的坑

介绍 手头上正好有个项目,需要做一个微信端H5视频秀的一个项目,想想好像挺简单的,由两个视频组成,播放完第一个视频后点击按钮继而播放第二个视频。好了,结果微信的坑TM的多 问题排查 自...

🚲Allen ⋅ 05/18 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

骰子游戏代码开源地址

因为阿里云现在服务器已经停用了,所以上面的配置已经失效。 服务端开源地址:https://gitee.com/goalya/chat4.git 客户端开源地址:https://gitee.com/goalya/client4.git 具体运行界面请参考...

算法之名 ⋅ 32分钟前 ⋅ 0

设计模式--装饰者模式

装饰者模式 定义 动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式相比生成子类更为灵活。 通用类图 意图 动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式相比...

gaob2001 ⋅ 今天 ⋅ 0

JavaScript零基础入门——(八)JavaScript的数组

JavaScript零基础入门——(八)JavaScript的数组 欢迎大家回到我们的JavaScript零基础入门,上一节课我们讲了有关JavaScript正则表达式的相关知识点,便于大家更好的对字符串进行处理。这一...

JandenMa ⋅ 今天 ⋅ 0

sbt网络问题解决方案

转自:http://dblab.xmu.edu.cn/blog/maven-network-problem/ cd ~/.sbt/launchers/0.13.9unzip -q ./sbt-launch.jar 修改 vi sbt/sbt.boot.properties 增加一个oschina库地址: [reposit......

狐狸老侠 ⋅ 今天 ⋅ 0

大数据,必须掌握的10项顶级安全技术

我们看到越来越多的数据泄漏事故、勒索软件和其他类型的网络攻击,这使得安全成为一个热门话题。 去年,企业IT面临的威胁仍然处于非常高的水平,每天都会看到媒体报道大量数据泄漏事故和攻击...

p柯西 ⋅ 今天 ⋅ 0

Linux下安装配置Hadoop2.7.6

前提 安装jdk 下载 wget http://mirrors.hust.edu.cn/apache/hadoop/common/hadoop-2.7.6/hadoop-2.7.6.tar.gz 解压 配置 vim /etc/profile # 配置java环境变量 export JAVA_HOME=/opt/jdk1......

晨猫 ⋅ 今天 ⋅ 0

crontab工具介绍

crontab crontab 是一个用于设置周期性被执行的任务工具。 周期性执行的任务列表称为Cron Table crontab(选项)(参数) -e:编辑该用户的计时器设置; -l:列出该用户的计时器设置; -r:删除该...

Linux学习笔记 ⋅ 今天 ⋅ 0

深入Java多线程——Java内存模型深入(2)

5. final域的内存语义 5.1 final域的重排序规则 1.对于final域,编译器和处理器要遵守两个重排序规则: (1)在构造函数内对一个final域的写入,与随后把这个被构造对象的引用赋值给一个引用...

江左煤郎 ⋅ 今天 ⋅ 0

面试-正向代理和反向代理

面试-正向代理和反向代理 Nginx 是一个高性能的反向代理服务器,但同时也支持正向代理方式的配置。

秋日芒草 ⋅ 今天 ⋅ 0

Spring 依赖注入(DI)

1、Setter方法注入: 通过设置方法注入依赖。这种方法既简单又常用。 类中定义set()方法: public class HelloWorldOutput{ HelloWorld helloWorld; public void setHelloWorld...

霍淇滨 ⋅ 昨天 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部