iOS 进阶

iOS 常用宏定义

2022-03-08  本文已影响0人  假如兔子失了尾

常用定义

//加载图片
#define GetImage(imageName) [UIImage imageNamed:[NSString stringWithFormat:@"%@",imageName]]

//字体
#define FONT_SIZE(f) [UIFont systemFontOfSize:(f)]//不加粗
#define FONT_B_SIZE(f) [UIFont boldSystemFontOfSize:(f)]//加粗
#define NameFont(x) [UIFont fontWithName:@"PingFangSC-Light"size:x]//苹方细体
#define NameBFont(x) [UIFont fontWithName:@"PingFangSC-Regular"size:x]//苹方体
#define NumFont(x) [UIFont fontWithName:@"Helvetica Neue"size:x]//数字字体
#define Customize(name,x) [UIFont fontWithName:name size:x]//自定义字体

//弱引用self(用于block块中)
#define WS(weakSelf) __weak __typeof(&*self)weakSelf = self;

// alert
#define Alert(_S_, ...) [[[UIAlertView alloc] initWithTitle:@"提示"message:[NSString stringWithFormat:(_S_), ##__VA_ARGS__] delegate:nil cancelButtonTitle:@"知道了"otherButtonTitles:nil] show]

#pragma mark- View设置
// View 圆角和加边框

#define ViewBorderRadius(view, Radius, Width, Color)\
\
[view.layer setCornerRadius:(Radius)];\
[view.layer setMasksToBounds:YES];\
[view.layer setBorderWidth:(Width)];\
[view.layer setBorderColor:[Color CGColor]]

// View 圆角
#define ViewRadius(view, Radius)\
\
[view.layer setCornerRadius:(Radius)];\
[view.ayer setMasksToBounds:YES]

// View 阴影
#define ViewShadow(view,color,size,alpha,radius)\
\
view.layer.shadowColor = color.CGColor;\
view.layer.shadowOffset = size;\
view.layer.shadowOpacity = alpha;\
view.layer.shadowRadius = radius

// View 边框
#define ViewBorder(view, Color, Width)\
\
[view.layer setBorderWidth:(Width)];\
[view.layer setBorderColor:(Color).CGColor]

#pragma mark- 系统信息
// 当前语言
#define CURRENTLANGUAGE ([[NSLocale preferredLanguages] objectAtIndex:0])

// app版本号
#define VERSION (NSString *)[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]

// app Build版本号
#define BUILD (NSString *)[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]

#pragma mark- 判空
//字符串是否为空
#define ISNullString(str) ([str isKindOfClass:[NSNull class]] || str == nil || [str length] <1? YES : NO )

//数组是否为空
#define ISNullArray(array) (array == nil || [array isKindOfClass:[NSNull class]] || array.count ==0||[array isEqual:[NSNull null]])

//字典是否为空
#define ISNullDict(dic) (dic == nil || [dic isKindOfClass:[NSNull class]] || dic.allKeys ==0|| [dic isEqual:[NSNull null]])

//是否是空对象
#define ISNullObject(_object) (_object == nil \
|| [_object isKindOfClass:[NSNull class]] \
|| ([_object respondsToSelector:@selector(length)] && [(NSData *)_object length] ==0) \
|| ([_object respondsToSelector:@selector(count)] && [(NSArray *)_object count] ==0))

#pragma mark- 日志
//自定义Log
#ifdef DEBUG
    #define NSLog(FORMAT, ...) fprintf(stderr,"%s:%d\t%s\n",[[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], __LINE__, [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#else
    #define NSLog(FORMAT, ...) nil
#endif

#pragma mark- 持久化存储
//永久存储对象
#define SetUserDefaults(object, key) \
({ \
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults]; \
[defaults setObject:object forKey:key]; \
[defaults synchronize]; \
})

//获取对象
#define GetUserDefaults(key) [[NSUserDefaults standardUserDefaults] objectForKey:key]

//删除某一个对象
#define kRemoveUserDefaults(key) \
({ \
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; \
[defaults removeObjectForKey:_key]; \
[defaults synchronize]; \
})

//清除 NSUserDefaults 保存的所有数据
#define kRemoveAllUserDefaults  [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]]

#pragma mark- 时间对象
// 秒数
#define Seconds(Days) (24.f * 60.f * 60.f * (Days))
// 毫秒数
#define Milliseconds(Days) (24.f * 60.f * 60.f * 1000.f * (Days))
//获得当前的年份
#define  CurrentYear [[NSCalendar currentCalendar] component:NSCalendarUnitYear fromDate:[NSDate date]]
//获得当前的月份
#define  CurrentMonth [[NSCalendar currentCalendar] component:NSCalendarUnitMonth fromDate:[NSDate date]]
//获得当前的日期
#define  CurrentDay  [[NSCalendar currentCalendar] component:NSCalendarUnitDay fromDate:[NSDate date]]
//获得当前的小时
#define  CurrentHour [[NSCalendar currentCalendar] component:NSCalendarUnitHour fromDate:[NSDate date]]
//获得当前的分
#define  CurrentMin [[NSCalendar currentCalendar] component:NSCalendarUnitMinute fromDate:[NSDate date]]
//获得当前的秒
#define  CurrentSec [[NSCalendar currentCalendar] component:NSCalendarUnitSecond fromDate:[NSDate date]]

常用颜色

// 颜色(RGB)
#define RGB(r, g, b) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1]
#define RGBA(r, g, b, a) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:(a)]

// 颜色(16进制)
#define HexColor(hexValue) [UIColor colorWithRed:((float)((hexValue & 0xFF0000) >> 16)) / 255.0 green:((float)((hexValue & 0xFF00) >> 8)) / 255.0 blue:((float)(hexValue & 0xFF)) / 255.0 alpha:1.0f]
#define HexAlphaColor(hexValue, alpha) [UIColor colorWithRed:((float)((hexValue & 0xFF0000) >> 16)) / 255.0 green:((float)((hexValue & 0xFF00) >> 8)) / 255.0 blue:((float)(hexValue & 0xFF)) / 255.0 alpha:alpha]

// 随机颜色
#define RandomColor [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1]

文件夹/文件路径

//获取沙盒 temp
#define PathTemp NSTemporaryDirectory()
//获取沙盒 Document
#define PathDocument [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]
//获取沙盒 Cache
#define PathCache [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]

//Document路径下文件/文件夹
#define DocumentPath(res) [PathDocument stringByAppendingPathComponent:res]
//Cache路径下文件/文件夹
#define CachePath(res) [PathCache stringByAppendingPathComponent:res]
//Temp路径下文件/文件夹
#define TempPath(res) [PathTemp stringByAppendingPathComponent:res]

frame设置

//是否是手机

#define IS_iPhone ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)

//是否是iPad
#define IS_iPad ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)

//屏幕宽
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width

//屏幕高
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

//屏幕frame
#define SCREEN_FRAME [UIScreen mainScreen].bounds

// 判断iPhone4系列
#define IsiPhone4 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) && !IsPad : NO)
// 判断iPhone5系列
#define IsiPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) && !IsPad : NO)
// 判断iPhone6系列
#define JS_isiPhone6 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(750, 1334), [[UIScreen mainScreen] currentMode].size) && !IsPad : NO)
//判断iphone6+系列
#define IsiPhone6Plus ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size) && !IsPad : NO)
// 判断iPhoneX
#define IsIPhone_X ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) && !IsPad : NO)
// 判断iPHoneXr | 11
#define IsIPhone_Xr ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(828, 1792), [[UIScreen mainScreen] currentMode].size) && !IsPad : NO)
// 判断iPhoneXs | 11Pro
#define IsIPhone_Xs ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) && !IsPad : NO)
// 判断iPhoneXs Max | 11ProMax
#define IsIPhone_Xs_Max ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2688), [[UIScreen mainScreen] currentMode].size) && !IsPad : NO)
//判断iPhone12_Mini
#define IsIPhone_iPhone12_Mini ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1080, 2340), [[UIScreen mainScreen] currentMode].size) && !IsPad : NO)
//判断iPhone12 | 12Pro
#define IsIPhone_iPhone12 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1170, 2532), [[UIScreen mainScreen] currentMode].size) && !IsPad : NO)
//判断iPhone12 Pro Max
#define IsIPhone_iPhone12_ProMax ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1284, 2778), [[UIScreen mainScreen] currentMode].size) && !IsPad : NO)

//6为标准适配的,如果需要其他标准可以修改
#define Scale_W(w) (SCREEN_WIDTH/375) * (w)
#define Scale_H(h) (SCREEN_HEIGHT/667) * (h)

//statusbar的高度
#define STATUS_HEIGHT ((IS_IPHONE_X || IS_IPHONE_Xr || IS_IPHONE_Xs || IS_IPHONE_Xs_Max) == NO ?20.0:44.0)

//navigation高度 (带statusbar)
#define NAVGATION_HEIGHT ((IS_IPHONE_X || IS_IPHONE_Xr || IS_IPHONE_Xs || IS_IPHONE_Xs_Max) == NO ?64.0:88.0)

//底部安全高度
#define BOTTOM_HEIGHT  ((IS_IPHONE_X || IS_IPHONE_Xr || IS_IPHONE_Xs || IS_IPHONE_Xs_Max) == NO ?0.0:34.0)

// View 坐标(x,y)和宽高(width,height)
#define X(v)                    (v).frame.origin.x
#define Y(v)                    (v).frame.origin.y
#define WIDTH(v)                (v).frame.size.width
#define HEIGHT(v)              (v).frame.size.height
#define MinX(v)                CGRectGetMinX((v).frame)
#define MinY(v)                CGRectGetMinY((v).frame)
#define MidX(v)                CGRectGetMidX((v).frame)
#define MidY(v)                CGRectGetMidY((v).frame)
#define MaxX(v)                CGRectGetMaxX((v).frame)
#define MaxY(v)                CGRectGetMaxY((v).frame)

GCD多线程、父视图获取

//延迟执行
CG_INLINE void runTime(CGFloat time ,dispatch_block_t block) {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), block);
}

//回到主线程
CG_INLINE void runMain(dispatch_block_t block){
    dispatch_async(dispatch_get_main_queue(), block);
}

//只运行一次
CG_INLINE void runOnce(dispatch_block_t block){
    staticdispatch_once_tonceToken;
    dispatch_once(&onceToken, block);
}

//开辟异步线程
CG_INLINE void runAsyn(dispatch_block_t block){
    dispatch_async(dispatch_get_global_queue(0, 0), block);
}

//获取当前view视图的父类控制器
CG_INLINE UIViewController* superViewController(UIView *view){
    UIResponder*next = [viewnextResponder];
    do{
        if([nextisKindOfClass:[UIViewControllerclass]]) {
            return(UIViewController*)next;
        }next = [nextnextResponder];
    }while(next !=nil);
    return nil;
}
上一篇 下一篇

猜你喜欢

热点阅读