【开发工具】常用方法

1,汉子转拼音

    NSMutableString *ms = [[NSMutableString alloc] initWithString:@"我要转成拼音"];
    // 去除音调
    if (CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformMandarinLatin, NO)) { 
    }
    // 转成拼音
    if (CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformStripCombiningMarks, NO)) {
    }
    
    // 大小写转换
    [ms lowercaseString]; // 小写
    [ms uppercaseString]; // 大写
    [ms capitalizedString]; // 字母开头大写

2,MD5

a,MD5加密
+ (NSString *)xh_md5String:(NSString *)string {
    
    if(string == nil || [string length] == 0)  return nil;
    
    const char *value = [string UTF8String];
    
    unsigned char outputBuffer[CC_MD5_DIGEST_LENGTH];
    CC_MD5(value, (CC_LONG)strlen(value), outputBuffer);
    
    NSMutableString *outputString = [[NSMutableString alloc] initWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(NSInteger count = 0; count < CC_MD5_DIGEST_LENGTH; count++){
        [outputString appendFormat:@"%02x",outputBuffer[count]];
    }
    return outputString;
}
b,获取文件MD5
+ (NSString *)md5WithData:(NSData *)data {
    unsigned char result[16];
    CC_MD5(data.bytes, data.length, result); 
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

3,图片数据解析成GIF


// 获取图片数据
NSData *data = [NSData dataWithContentsOfURL:imageUrl];

#import 

// 调用此方法,如果是GIF,则解析;不是,直接返回图片
+ (UIImage *)xh_animatedGIFWithData:(NSData *)data{
    if (!data) {
        return nil;
    }
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    size_t count = CGImageSourceGetCount(source);
    
    UIImage *animatedImage;
    if (count <= 1) {
        animatedImage = [[UIImage alloc] initWithData:data];
    }else {
        NSMutableArray *images = [NSMutableArray array];
        NSTimeInterval duration = 0.0f;
        for (size_t i = 0; i < count; i++) {
            CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);  
            duration += [self xh_frameDurationAtIndex:i source:source];
            [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];
            CGImageRelease(image);
        }
        if (!duration) {
            duration = (1.0f / 10.0f) * count;
        }
        animatedImage = [UIImage animatedImageWithImages:images duration:duration];
    }
    CFRelease(source);
    return animatedImage;
}

+ (float)xh_frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source {
    float frameDuration = 0.1f;
    CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil);
    NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties;
    NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary];
    NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime];
    if (delayTimeUnclampedProp) {
        frameDuration = [delayTimeUnclampedProp floatValue];
    }
    else {
        NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime];
        if (delayTimeProp) {
            frameDuration = [delayTimeProp floatValue];
        }
    }
    if (frameDuration < 0.011f) {
        frameDuration = 0.100f;
    } 
    CFRelease(cfFrameProperties);
    return frameDuration;
}

4,常用的时间处理

+ (NSString *)created_at:(NSString*)time{
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *begin = [fmt dateFromString:time];
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *cmps = [calendar components:unit fromDate:begin toDate:now options:0];
    
    if ([begin isThisYear]) { // 今年
        if ([begin isYesterday]) { // 昨天
            fmt.dateFormat = @"昨天 HH:mm";
            return [fmt stringFromDate:begin];
        } else if ([begin isToday]) { // 今天
            if (cmps.hour >= 1) {
                fmt.dateFormat = @"今天 HH:mm";
                return [fmt stringFromDate:begin];
                //                return [NSString stringWithFormat:@"%d小时前", (int)cmps.hour];
            } else if (cmps.minute >= 1) {
                return [NSString stringWithFormat:@"%d分钟前", (int)cmps.minute];
            } else {
                return @"刚刚";
            }
        } else { // 今年的其他日子
            fmt.dateFormat = @"MM月dd日 HH:mm";
            return [fmt stringFromDate:begin];
        }
    } else { // 非今年
        fmt.dateFormat = @"yyyy年MM月dd日 HH:mm";
        return [fmt stringFromDate:begin];
    }
}

/**
 *  判断某个时间是否为今年
 */
- (BOOL)isThisYear{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // 获得某个时间的年月日时分秒
    NSDateComponents *dateCmps = [calendar components:NSCalendarUnitYear fromDate:self];
    NSDateComponents *nowCmps = [calendar components:NSCalendarUnitYear fromDate:[NSDate date]];
    return dateCmps.year == nowCmps.year;
}

5,设置任意一个圆角

// rect:视图的大小   byRoundingCorners:设置左上和右上圆角
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, WIDTH, CKAGEDITVIEW_BACKGROUNDVIEW_HEIGHT) byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)]; // UIRectCornerBottomRight通过这个设置
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = self.backgroundView.bounds;
maskLayer.path = maskPath.CGPath;
// self.backgroundView 为需要设置圆角的视图
 self.backgroundView.layer.mask = maskLayer;

6,常用函数

1,取整

// 向上取整
ceil(f)
// 向下取整
floor(f)

2,四舍五入

float f = 1.5;
int a;
a = (int)(f+0.5);
NSLog("a = %d",a);

7,数字转中文

- (NSString*)convert:(NSString*)str{
    if (!str||[str isEqualToString:@""]) return nil;
    NSMutableString*newStr=[[NSMutableString alloc]initWithString:str];
    while ([newStr hasPrefix:@"0"]){
        [newStr deleteCharactersInRange:NSMakeRange(0, 1)];
    }
    if (!newStr || [newStr isEqualToString:@""]) return nil;
    if ([newStr length]>12)return nil;
    NSString*string;
    NSMutableString*result=[[NSMutableString alloc]initWithCapacity:1];
    if ([newStr length]>8){
        string=[newStr substringToIndex:[newStr length]-8];
        [result appendString:[self subConvert:string]];
        [result appendFormat:@"亿"];
        [newStr deleteCharactersInRange:NSMakeRange(0, [newStr length]-8)];
    }
    if ([newStr length]>4){
        string=[newStr substringToIndex:[newStr length]-4];
        if (![string isEqual:@"0000"]){
            if ([string hasPrefix:@"0"]){
                [result appendFormat:@"零"];
            }
            [result appendString:[self subConvert:string ]];
            [result appendFormat:@"万"];
        }
        [newStr deleteCharactersInRange:NSMakeRange(0, [newStr length]-4)];
    }
    string=newStr;
    if (![string isEqual:@"0000"]){
        if ([string hasPrefix:@"0"]){
            [result appendFormat:@"零"];
        }
        [result appendString:[self subConvert:string]];
    }
    return result;
}

- (NSString *)subConvert:(NSString *)str{
    if (!str) return nil;
    NSInteger len=[str length];
    if (len>4)return nil;
    NSMutableString*newStr=[[NSMutableString alloc] initWithString:str];
    while ([newStr hasPrefix:@"0"]){
        [newStr deleteCharactersInRange:NSMakeRange(0, 1)];
    }
    if (!newStr||[newStr isEqualToString:@""]) return nil;
    int isZero=0;
    NSMutableString*result=[[NSMutableString alloc]initWithCapacity:1];
    NSString*referenceStr=@"零一二三四五六七八九十"; // 零壹贰叁肆伍陆柒捌玖
    NSString*positionRef=@"个十百千"; // 个拾百仟
    len=[newStr length];
    for (int i=0; i

8,base65转码

+ (NSString *)base64:(NSString *)string {
    NSData *sampleData = [string dataUsingEncoding:NSUTF8StringEncoding];
    return [sampleData base64EncodedStringWithOptions:0];
}

9,计算文件夹大小

- (NSInteger)fileSize{
    NSFileManager *mgr = [NSFileManager defaultManager];
    // 判断是否为文件
    BOOL dir = NO;
    BOOL exists = [mgr fileExistsAtPath:self isDirectory:&dir];
    // 文件\文件夹不存在
    if (exists == NO) return 0;
    
    if (dir) { // self是一个文件夹
        // 遍历caches里面的所有内容 --- 直接和间接内容
        NSArray *subpaths = [mgr subpathsAtPath:self];
        NSInteger totalByteSize = 0;
        for (NSString *subpath in subpaths) {
            // 获得全路径
            NSString *fullSubpath = [self stringByAppendingPathComponent:subpath];
            // 判断是否为文件
            BOOL dir = NO;
            [mgr fileExistsAtPath:fullSubpath isDirectory:&dir];
            if (dir == NO) { // 文件
                totalByteSize += [[mgr attributesOfItemAtPath:fullSubpath error:nil][NSFileSize] integerValue];
            }
        }
        return totalByteSize;
    } else { // self是一个文件
        return [[mgr attributesOfItemAtPath:self error:nil][NSFileSize] integerValue];
    }
}

10,通过backgroundColor设置控制器的背景图片

//设置背景(注意这个图片其实在根图层)
UIImage *backgroundImage=[UIImage imageNamed:@"background.jpg"];
self.view.backgroundColor=[UIColor colorWithPatternImage:backgroundImage];

11,提示弹框添加一个动画效果,可以在显示的时候添加这一段代码

- (void)show{
    // self.backgroudView 是提示框的背景视图,承载提示框内的所有控件
    self.backgroundView.layer.opacity = 0.5f;
    self.backgroundView.layer.transform = CATransform3DMakeScale(1.3f, 1.3f, 1.0);
    [UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         self.backgroundView.layer.opacity = 1.0f;
                         self.backgroundView.layer.transform = CATransform3DMakeScale(1, 1, 1);
                     }
                     completion:NULL
     ];
}

12,判断控制器是push还是modal

  NSArray *viewcontrollers=self.navigationController.viewControllers;
   if (viewcontrollers.count>1) {
        if ([viewcontrollers objectAtIndex:viewcontrollers.count-1]==self) {
            //push方式
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    else{
        //present方式
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }

13,获取视图所在的控制器

- (UIViewController*)viewController{
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}

- (UIViewController *)currentController {
    UIResponder *nextResponder = self.nextResponder;
    while (![nextResponder isKindOfClass: [UIWindow class]]) {
        if ([nextResponder isKindOfClass: [UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
        nextResponder = nextResponder.nextResponder;
    }
    return nil;
}

14,获取视图的根控制器

/* 获取根视图控制器 */
+ (UIViewController *)getRootViewController {
    UIWindow *widow = [UIApplication sharedApplication].keyWindow;
    UIViewController *topVc = widow.rootViewController;
    while (topVc.presentedViewController) {
        topVc = topVc.presentedViewController;
    }
    return topVc;
}

15,添加侧滑手势

#import "UIViewController+AGExtension.h"
@implementation UIViewController (AGExtension)
- (void)setupEdgeGestureRecognizer{

  #pragma mark- 添加边缘侧滑手势:
    UIScreenEdgePanGestureRecognizer *edgGes = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(pushBackBarButtonItemAction:)];
  #pragma mark- 设置侧滑的方向:
    edgGes.edges = UIRectEdgeLeft;
    edgGes.delegate = self;
    [self.view addGestureRecognizer:edgGes];
}

- (void)pushBackBarButtonItemAction:(UIBarButtonItem *)item{
//    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

// 是否支持多个手势
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    // 1
//    if ([gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]]  && [otherGestureRecognizer isKindOfClass:[UIScreenEdgePanGestureRecognizer class]]) {
//        return YES;
//    } else  {
//        return NO;
//    }
    // 2
    if ([gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]]) {
        return YES;
    } else  {
        return NO;
    }
}
@end

注意 1 和 2 的区别
1 有判断手势是否是UIScreen上的手势,2 没有
如果是要实现某一个界面上添加侧滑手势,使用 1
使用 2 的场景:

在一个多标签的控制器中,包含多个可以左右滑动切换的tableView的情况下,侧滑返回将会失效(对应上面的处理方法,[gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]] 的值是NO)。
如果使用 2 ,则每个页面的侧滑都能够被接收到,控制器就能够成功返回。弊端还没发现


15,pop回某个页面

  • 要到某个界面,可以通过便利控制器,找到指定的控制器
  • 更多查看下面链接
    http://blog.csdn.net/justinjing0612/article/details/7360852

16,隐藏

隐藏导航栏

[self.navigationController setNavigationBarHidden:YES animated:NO];

隐藏状态了

[[UIApplication sharedApplication] setStatusBarHidden:NO];

17,ARC下获取引用计数

- (NSInteger)retainCount:(id)obj{
    NSInteger count = CFGetRetainCount((__bridge void *)obj);
    NSLog(@"{\n%@:\n}", obj, count);
    return count;
}

18,宏定义 block 回调写法

#define XM_SAFE_BLOCK(BlockName, ...) ({ !BlockName ? nil : BlockName(__VA_ARGS__); })

19,绘制虚线

- (void)drawLineInView:(UIView *)view {
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayer setBounds:view.bounds];
    [shapeLayer setPosition:view.center];
    [shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
    // 设置虚线颜色为blackColor [shapeLayer setStrokeColor:[[UIColor blackColor] CGColor]];
    [shapeLayer setStrokeColor:COLOR_BUTTON_GREEN.CGColor];
    // 3.0f设置虚线的宽度
    [shapeLayer setLineWidth:0.5f];
    [shapeLayer setLineJoin:kCALineJoinRound];
    // 3=线的宽度 1=每条线的间距
    [shapeLayer setLineDashPattern:@[@4, @4]];
    // Setup the path CGMutablePathRef path = CGPathCreateMutable();
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, 0);
    CGPathAddLineToPoint(path, NULL, view.width,0);
    [shapeLayer setPath:path];
    CGPathRelease(path);
    [view.layer addSublayer:shapeLayer];
}

20,通过颜色绘制图片

+ (UIImage *)ag_imageWithColor:(UIColor *)color{

    CGSize imageSize = CGSizeMake(50, 50);
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);

    UIBezierPath *p = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];
    [color setFill];
    [p fill];
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;
}


你可能感兴趣的:(【开发工具】常用方法)