IOS - 常用宏定义和功能方法

update 17-01-10
17-01-10:添加为UIView添加毛玻璃方法

+ (void)addVisualEffectViewForView:(UIView *)view withStyle:(UIBlurEffectStyle)style andIfSendToBack:(BOOL)isSendBack
{
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:style];
    UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc]initWithEffect:blurEffect];
    blurEffectView.frame = view.bounds;
    [view addSubview:blurEffectView];
    if (isSendBack) {
        [view sendSubviewToBack:blurEffectView];
    }
}

17-01-04:添加视图复制方法 C+F:(duplicateView)

github download click here

.h


/************************Tools***********************/

#pragma mark - 存网络请求参数或者其他类似key value对应的字典
@property (nonatomic,strong) NSDictionary *keyValueDic;

+ (instancetype)sharedCommonUse;


#pragma mark - 时间相关

#pragma mark - 获取当前时间
+ (NSString *)getCurrentTime;

#pragma mark - 将日期格式转化成字符串
+(NSString*)getFormatedTime:(NSDate*)date;

#pragma mark - date->string
+(NSString *)stringWithDate:(NSDate *)date Format:(nullable NSString *)fmt;

#pragma mark - string->date
+(NSDate *)dateWithString:(NSString *)stringDate Format:(NSString *)fmt;

#pragma mark - 将总秒数转换成 x天x小时x分钟x秒
+(NSString *)countdownTimeFrom:(NSTimeInterval)ti;

#pragma mark - 两个nsdate相差的天数 
+(NSInteger)getDaysFrom:(NSDate *)serverDate To:(NSDate *)endDate;


#pragma mark - 当前版本号
+(NSString *)currentVersion;

#pragma mark - 判断这个ad在此用户是否显示过(uid + md5 判断)
+ (BOOL)ifThisADBannerHaveOnceShowed:(NSString *)md5;

#pragma mark - 改变图片大小
+(UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize;

#pragma mark - 拨打电话
+ (void)callSomebody:(NSString *)tel;

#pragma mark - 字符串是否为数字
+ (BOOL)ifThisStringIsAnNumber:(NSString *)str;

#pragma mark - 字符串是否为整形
+ (BOOL)isPureInt:(NSString*)string;

#pragma mark - 判断是否为浮点形
+ (BOOL)isPureFloat:(NSString*)string;

#pragma mark - 关闭所有键盘
+ (void)resignFirstResponder;

#pragma mark - keyWindow
+ (UIWindow *)keyWindow;

#pragma mark - view层级设置最上
+ (void)bringViewToFrontAllTime:(UIView *)view;

#pragma mark - 复制视图
+ (UIView *)duplicateView:(UIView*)view;

#pragma mark - vc栈

#pragma mark - 从栈中将要移动vc向前移动index个位置,中间的vc将被释放
//ex:pay success pop start vc
+ (void)moveForwardTopVC:(UIViewController *)vc ForwardIndex:(NSInteger)index;

#pragma mark - pop到指定名字的VC,没有index可能变化的引起的问题
+ (void)popToViewControllerWithVC:(UIViewController *)vc toClass:(Class)toClass animated:(BOOL)animated;

#pragma mark - 当前栈中是否含有 class 这个类的实例存在
+(BOOL)currentStackisContainClass:(Class)className withCurrentVC:(UIViewController *)vc;

#pragma mark - 从栈中移动vc 到指定序号
+(void)moveForwardTopVC:(UIViewController *)vc ToIndex:(NSInteger)index  FormStackWithNavigationController:(UINavigationController *)nav;

#pragma mark - 从oldVC的栈中 ,使用newVC 替换 oldVC
+(void)replaceOldVC:(UIViewController *)oldVC NewVC:(UIViewController *)newVC;


#pragma mark - 传入数据字典&Model名打印出Model Body
+(void)createModelWithDictionary:(NSDictionary *)dict modelName:(NSString *)modelName;

#pragma mark - 计算字符串高度
- (float) calculateStrheightWithStr:(NSString *)str Font: (UIFont *)font Width: (float) width;

#pragma mark - 计算字符串宽度
- (float) calculateStrwidthWithStr:(NSString *)str Font: (UIFont *) font;

#pragma mark - 将一个UIView切成圆形 宽高得相等
+ (void)changeViewToCircle:(UIView *)view;

#pragma mark - collectionView 重新加载数据后计算出高度并更新
+ (void)reloadCollectionViewHeight:(UICollectionView *)collectionView;

// Factory

#pragma mark - 创建btn 基本属性: frame title titleColor backgroundColor
+ (UIButton *)createButtonWithFrame:(CGRect)frame Title:(NSString *)title TitleColor:(UIColor *)titleColor BackgroundColor:(UIColor *)backgroundColor;

#pragma mark - 创建btn 基本属性 + 边框 + 圆角 + 背景图
+ (UIButton *)createButtonWithFrame:(CGRect)frame Title:(NSString *)title TitleColor:(UIColor *)titleColor BackgroundColor:(UIColor *)backgroundColor CornerRadius:(CGFloat)cornerRadius BorderWidth:(CGFloat)borderWidth BorderColor:(UIColor *)borderColor ImageName:(NSString *)imageName;

#pragma mark - 创建label 基本属性 frame text font textColor
+ (UILabel *)createLabelWithFrame:(CGRect)frame Text:(NSString *)text Font:(UIFont *) font TextColor:(UIColor *)textColor;

#pragma mark - 创建label 基本属性 + backgroundColor + textAlinment 
+ (UILabel *)createLabelWithFrame:(CGRect)frame Text:(NSString *)text Font:(UIFont *) font TextColor:(UIColor *)textColor BackgroundColor:(UIColor *)backgroundColor TextAlignment:(NSTextAlignment)textAlinment;

#pragma mark - 富文本单个keyword
+(NSAttributedString *)attributeTextStr:(NSString *)text textColor:(UIColor *)textColor textFont:(UIFont *)textFont  keywordStr:(NSString *)keywordStr keywordColor:(UIColor *)keywordColor keywordFont:(UIFont *)keywordFont;

#pragma mark - 富文本多个keyword
+(NSAttributedString *)attributeTextStr:(NSString *)text textColor:(UIColor *)textColor textFont:(UIFont *)textFont keywordStrArray:(NSArray *)keywordStrArray keywordColor:(UIColor *)keywordColor keywordFont:(UIFont *)keywordFont;


@end

NS_ASSUME_NONNULL_END

/************************Define************************/

#ifdef DEBUG
#define QZLog(fmt, ...) NSLog((@"owner:QZ  %s  [Line %d] \n " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#define QZLog(...)
#endif

//判断是真机还是模拟器
#if TARGET_OS_IPHONE
//iPhone Device
#endif

#if TARGET_IPHONE_SIMULATOR
//iPhone Simulator
#endif

#define SYSTEM_VERSION [[[UIDevice currentDevice] systemVersion] floatValue]
#define IS_IOS7 ([[UIDevice currentDevice].systemVersion doubleValue] >= 7.0]

#pragma mark - RGB颜色
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
#define COLOR(R, G, B, A) [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:A]

#define DEVICE_HEIGHT  ([[UIScreen mainScreen] bounds].size.height)
#define DEVICE_WIDTH   ([[UIScreen mainScreen] bounds].size.width)
#define SCREEN_HEIGHT  DEVICE_HEIGHT
#define SCREEN_WIDTH   DEVICE_WIDTH
#define NavigationBar_Height 44

/************************适配************************/
#define IS_IPHONEUI   (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_IPADUI     (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define IS_IPHONE4     ((int)DEVICE_HEIGHT%480==0)
#define IS_IPHONE5     ((int)DEVICE_HEIGHT%568==0)
#define IS_IPAD        ((int)DEVICE_HEIGHT%1024==0)
#define IS_IPHONE6      ((int)DEVICE_HEIGHT%667==0)
#define IS_IPHONE6P     ((int)DEVICE_HEIGHT%736==0)
/*
 4    inch 320*568
 4.7  inch 375*667
 5.5  inch 414*736
 */
#define CONVERT_SCALE(x) (x)/2

#define CT_SCALE_X      DEVICE_WIDTH/320.0
#define CT_SCALE_Y      DEVICE_HEIGHT/568.0
// 5  6  比例一致,6p 放大
#define CT6P_SCALE_X      (IS_IPHONE6P?CT_SCALE_X:1)
#define CT6P_SCALE_Y      (IS_IPHONE6P?CT_SCALE_Y:1)
//转化为最低兼容设备尺寸
#define ConvertTo5_W(x) (CONVERT_SCALE(x)*320)/375
#define ConvertTo5_H(x) (CONVERT_SCALE(x)*568)/667

#define CW(x) ConvertTo5_W(x)*CT_SCALE_X
#define CH(x) ConvertTo5_H(x)*CT_SCALE_Y
#define CWFor6P(x) ConvertTo5_W(x)*CT6P_SCALE_X
#define CHFor6P(x) ConvertTo5_H(x)*CT6P_SCALE_Y

.m

+ (instancetype)sharedCommonUse
{
    static CommonUse *commonUse = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        commonUse = [[CommonUse alloc] init];
    });
    return commonUse;
}

- (NSDictionary*)keyValueDic
{
    if (!_keyValueDic) {
        NSDictionary *keyValueDic=[[NSDictionary alloc] init];
        keyValueDic = @{
                        @"key1":@"value1",
                        @"key2":@"value2",
                        @"key3":@"value3",
                        };
        _keyValueDic = keyValueDic;
    }
    return _keyValueDic;
}

+(NSString*)getCurrentTime{
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateTime=[formatter stringFromDate:[NSDate date]];
    return dateTime;
}

+(NSString*)getFormatedTime:(NSDate*)date{
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateTime=[formatter stringFromDate:date];
    return dateTime;

}

+(NSString *)stringWithDate:(NSDate *)date Format:(nullable NSString *)fmt
{
    NSDateFormatter *df = [[NSDateFormatter alloc]init];//格式化
    [df setDateFormat:fmt?:@"yyyy-MM-dd HH:mm"];

    return [df stringFromDate:date];
}

+(NSDate *)dateWithString:(NSString *)stringDate Format:(NSString *)fmt
{
    NSDateFormatter *df = [[NSDateFormatter alloc]init];//格式化
    [df setDateFormat:fmt?:@"yyyy-MM-dd HH:mm:ss"];

    return [df dateFromString:stringDate];
}

+(NSString *)countdownTimeFrom:(NSTimeInterval)ti
{
    NSCalendar *calendar = [NSCalendar currentCalendar];

    // 目标时间
    NSDate *targetDate = [NSDate dateWithTimeIntervalSince1970:ti];
    // 当前时间
    NSDate *today = [NSDate dateWithTimeIntervalSince1970:0];
    unsigned int unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    // 计算时间差
    NSDateComponents *d = [calendar components:unitFlags fromDate:targetDate toDate:today options:0];
    // 倒计时显示
    NSString *strDate = [NSString stringWithFormat:@"%ld天%ld小时%ld分%ld秒",(long)[d day], (long)[d hour], (long)[d minute], [d second]];
    strDate = [strDate stringByReplacingOccurrencesOfString:@"-" withString:@""];

    return strDate;
}

+(NSInteger)getDaysFrom:(NSDate *)serverDate To:(NSDate *)endDate
{
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    [gregorian setFirstWeekday:2];

    //去掉时分秒信息
    NSDate *fromDate;
    NSDate *toDate;
    [gregorian rangeOfUnit:NSCalendarUnitDay startDate:&fromDate interval:NULL forDate:serverDate];
    [gregorian rangeOfUnit:NSCalendarUnitDay startDate:&toDate interval:NULL forDate:endDate];
    NSDateComponents *dayComponents = [gregorian components:NSCalendarUnitDay fromDate:fromDate toDate:toDate options:0];

    return dayComponents.day;
}

+(NSString *)currentVersion
{
    return  [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
}


+ (BOOL)ifThisADBannerHaveOnceShowed:(NSString *)md5
{
    NSArray *array = [[NSUserDefaults standardUserDefaults] valueForKey:[NSString stringWithFormat:@"sawAdMd5%@",@"this is user id"]];
    return [array containsObject:md5];
}


+(UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize{
    UIGraphicsBeginImageContext(reSize);
    [image drawInRect:CGRectMake(0, 0, reSize.width, reSize.height)];
    UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return reSizeImage;
}

+(void)callSomebody:(NSString *)tel
{
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",tel];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [[UIApplication sharedApplication].keyWindow addSubview:callWebview];
}

+ (BOOL)ifThisStringIsAnNumber:(NSString *)str
{
    if ([self isPureInt:str] || [self isPureFloat:str]) {
        return YES;
    }
    return NO;
}

+ (BOOL)isPureInt:(NSString*)string
{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}

+ (BOOL)isPureFloat:(NSString*)string
{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return[scan scanFloat:&val] && [scan isAtEnd];
}

+ (void)resignFirstResponder
{
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
}

+ (UIWindow *)keyWindow
{
    return [[UIApplication sharedApplication].delegate window];
}

+ (void)bringViewToFrontAllTime:(UIView *)view
{
    view.layer.zPosition = MAXFLOAT;
    // 之后如果有View继续设置MAXFOAT,会更上层覆盖

}

+ (UIView *)duplicateView:(UIView*)view
{
    NSData * tempArchive = [NSKeyedArchiver archivedDataWithRootObject:view];
    return [NSKeyedUnarchiver unarchiveObjectWithData:tempArchive];
}

+(void)moveForwardTopVC:(UIViewController *)vc ForwardIndex:(NSInteger)index
{
    // 直接操作nav的viewControllers栈
    NSMutableArray *stackAry=[NSMutableArray arrayWithArray:vc.navigationController.viewControllers];

    for (NSInteger i=vc.navigationController.viewControllers.count-1; i>=vc.navigationController.viewControllers.count-1-index; i--) {
        if(i<0) return;
        [stackAry removeObjectAtIndex:i];
    }
    [stackAry addObject:vc];
    vc.navigationController.viewControllers=[stackAry copy];
}

+(void)popToViewControllerWithVC:(UIViewController *)vc toClass:(Class)toClass animated:(BOOL)animated
{
    for (UIViewController *controller in vc.navigationController.viewControllers) {
        if ([controller isKindOfClass:toClass]) {
            [vc.navigationController popToViewController:controller animated:animated];
        }
    }
}

+(BOOL)currentStackisContainClass:(Class)className withCurrentVC:(UIViewController *)vc;
{
    BOOL flag = NO;
    UINavigationController *nav = vc.navigationController;
    for (UIViewController *vc in nav.viewControllers) {
        if ([vc isKindOfClass:className]) {
            flag = YES;
            break;
        }
    }
    return flag;
}

+(void)moveForwardTopVC:(UIViewController *)vc ToIndex:(NSInteger)index  FormStackWithNavigationController:(UINavigationController *)nav
{
    NSMutableArray *stackAry=[NSMutableArray arrayWithArray:nav.viewControllers];

    for (NSInteger i=nav.viewControllers.count-1; i>=nav.viewControllers.count-1-index; i--) {
        if(i<0) return;
        [stackAry removeObjectAtIndex:i];
    }
    [stackAry addObject:vc];
    nav.viewControllers=[stackAry copy];
}

+(void)replaceOldVC:(UIViewController *)oldVC NewVC:(UIViewController *)newVC
{
    UINavigationController *nav = oldVC.navigationController;
    NSMutableArray *stackAry=[NSMutableArray arrayWithArray:nav.viewControllers];
    NSInteger index = [stackAry indexOfObject:oldVC];
    NSMutableArray *delArray = [NSMutableArray arrayWithObject:oldVC];
    [stackAry replaceObjectAtIndex:index withObject:newVC];
    nav.viewControllers = [stackAry copy];
    [delArray removeAllObjects];
}

+(void)createModelWithDictionary:(NSDictionary *)dict modelName:(NSString *)modelName
{
    printf("\n@interface %s :NSObject\n",modelName.UTF8String);
    for (NSString *key in dict) {
        NSString *type = ([dict[key] isKindOfClass:[NSNumber class]])?@"NSNumber":@"NSString";
        printf("@property (nonatomic,copy) %s *%s;\n",type.UTF8String,key.UTF8String);
    }
    printf("@end\n");

}


- (float) calculateStrheightWithStr:(NSString *)str Font: (UIFont *)font Width: (float) width
{
    CGRect textRect = [str boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
                                         options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
                                      attributes:@{NSFontAttributeName:font}
                                         context:nil];

    return ceil(textRect.size.height);
}

- (float) calculateStrwidthWithStr:(NSString *)str Font: (UIFont *) font
{
    CGRect textRect = [str boundingRectWithSize:CGSizeMake(MAXFLOAT, font.pointSize)
                                         options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                      attributes:@{NSFontAttributeName:font}
                                         context:nil];

    return ceil(textRect.size.width);
}

+ (void)changeViewToCircle:(UIView *)view
{
    view.layer.cornerRadius = view.bounds.size.width/2.0;
    view.clipsToBounds = YES;
}

+ (void)reloadCollectionViewHeight:(UICollectionView *)collectionView
{
    CGFloat x = collectionView.frame.origin.x;
    CGFloat y = collectionView.frame.origin.y;
    CGFloat width = collectionView.bounds.size.width;
    CGFloat height = collectionView.collectionViewLayout.collectionViewContentSize.height;
    collectionView.frame = CGRectMake(x, y, width, height);
}

+(NSAttributedString *)attributeTextStr:(NSString *)text textColor:(UIColor *)textColor textFont:(UIFont *)textFont  keywordStr:(NSString *)keywordStr keywordColor:(UIColor *)keywordColor keywordFont:(UIFont *)keywordFont
{
    return [CommonUse attributeTextStr:text textColor:textColor textFont:textFont keywordStrArray:keywordStr?@[keywordStr]:nil keywordColor:keywordColor keywordFont:keywordFont];
}

+(NSAttributedString *)attributeTextStr:(NSString *)text textColor:(UIColor *)textColor textFont:(UIFont *)textFont keywordStrArray:(NSArray *)keywordStrArray keywordColor:(UIColor *)keywordColor keywordFont:(UIFont *)keywordFont
{
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:text];
    [attr addAttributes:@{NSFontAttributeName:textFont?:[UIFont systemFontOfSize:17],NSForegroundColorAttributeName:textColor?:[UIColor blackColor]} range:NSMakeRange(0, text.length)];
    for (NSString *tempstr in keywordStrArray) {
        [attr addAttributes:@{NSFontAttributeName:keywordFont?:[UIFont systemFontOfSize:17],NSForegroundColorAttributeName:keywordColor?:[UIColor blackColor]} range:[text rangeOfString:tempstr]];
    }
    return attr;
}

/** Button Factory*/
+ (UIButton *)createButtonWithFrame:(CGRect)frame Title:(NSString *)title TitleColor:(UIColor *)titleColor BackgroundColor:(UIColor *)backgroundColor
{
    UIButton *btn = [[UIButton alloc] init];
    btn.frame = frame;
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:titleColor ? : [UIColor whiteColor] forState:UIControlStateNormal];
    btn.backgroundColor = backgroundColor ? :[UIColor whiteColor];
    return btn;
}

+ (UIButton *)createButtonWithFrame:(CGRect)frame Title:(NSString *)title TitleColor:(UIColor *)titleColor BackgroundColor:(UIColor *)backgroundColor CornerRadius:(CGFloat)cornerRadius BorderWidth:(CGFloat)borderWidth BorderColor:(UIColor *)borderColor ImageName:(NSString *)imageName
{
    UIButton *btn = [CommonUse createButtonWithFrame:frame Title:title TitleColor:titleColor BackgroundColor:backgroundColor];
        btn.layer.cornerRadius  = cornerRadius;
    if (borderWidth > 0) {
        btn.layer.borderWidth=borderWidth;
    }
    if (borderColor) {
        btn.layer.borderColor=[borderColor CGColor];
    }
    btn.layer.masksToBounds=YES;
    [btn setImage:[[UIImage imageNamed:imageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    return btn;
}

+ (UILabel *)createLabelWithFrame:(CGRect)frame Text:(NSString *)text Font:(UIFont *) font TextColor:(UIColor *)textColor
{
    UILabel *label = [[UILabel alloc] init];
    label.frame = frame;
    label.text = text ? :@"";
    if (font) {
        label.font = font;
    }
    if (textColor) {
        label.textColor = textColor;
    }
    return label;
}

+ (UILabel *)createLabelWithFrame:(CGRect)frame Text:(NSString *)text Font:(UIFont *) font TextColor:(UIColor *)textColor BackgroundColor:(UIColor *)backgroundColor TextAlignment:(NSTextAlignment)textAlinment
{
    UILabel *label = [CommonUse createLabelWithFrame:frame Text:text Font:font TextColor:textColor];
    if (backgroundColor) {
        label.backgroundColor = backgroundColor;
    }
    label.textAlignment = textAlinment;
    return label;
}

你可能感兴趣的:(IOS - 常用宏定义和功能方法)