我在iOS项目中常用的宏,提高不少效率,持续更新。。。

在项目中合理的使用一些宏,可以很大的提高代码效率,代码简洁度!下面我就列举一些我常用的宏,随着项目的进行,我会持续更新!

在这里呢,我一般是把常用宏分类写:基础宏,颜色宏,地址宏,通知文字等常量

  • 基础宏
/** MainScreen bounds */ 
#define Main_Screen_Bounds [[UIScreen mainScreen] bounds]
/** 屏幕宽高 */
#define kScreeWith [UIScreen mainScreen].bounds.size.width
#define kScreeHeight [UIScreen mainScreen].bounds.size.height

/** 状态栏的高度 */
/** 在iPhone x以前苹果手机的各机型状态栏高度均为20;
在iPhone x以后苹果新推出刘海屏机型,苹果的各机型状态栏高度均为44。
但是今年苹果随着苹果新操作系统iOS 14的推出导致了iPhone x以后的部分苹果刘海屏机型状态栏的高度的改变有的为47,有的为48,有的还是44。
目前这个更改不知道是ios 14.2的bug,还是说以后苹果会把刘海屏机型的状态栏的高度依然全部改成44。
iPhone X以前的机型     20
iPhone XR/11    48
iPhone X/11 Pro/ 11 Pro Max/12 mini    44
iPhone 12/12 Pro/Pro Max    47
*/
// #define kstatusBarSize [[UIApplication sharedApplication] statusBarFrame].size
// 获取状态栏高度
+ (CGFloat)getStatusBarHeight {
    CGFloat rz_statusBarHeight = 0;
    if (@available(iOS 13.0, *)) {
        UIStatusBarManager *statusBarManager = [UIApplication sharedApplication].windows.firstObject.windowScene.statusBarManager;
        rz_statusBarHeight = statusBarManager.statusBarFrame.size.height;
    }
    else {
        rz_statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
    }
    return rz_statusBarHeight;
}

// 导航栏高度(custom=44)+状态栏高度
// #define VIEW_TOP_HEIGHT (IOS7_OR_LATER ? 64.0f : 44.0f)  

/** 屏幕尺寸 */
#define IS_SCREEN_4_INCH    ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)
#define IS_SCREEN_35_INCH   ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO)
#define IS_SCREEN_47_INCH   ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(750, 1334), [[UIScreen mainScreen] currentMode].size) : NO)
#define IS_SCREEN_55_INCH   ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size) : NO)

/** 屏幕尺寸 */
#define is_screen_35_inch   CGSizeEqualToSize([UIScreen mainScreen].bounds.size, CGSizeMake(320, 480))
#define is_screen_40_inch   CGSizeEqualToSize([UIScreen mainScreen].bounds.size, CGSizeMake(320, 568))
#define is_screen_47_inch   CGSizeEqualToSize([UIScreen mainScreen].bounds.size, CGSizeMake(375, 667))
#define is_screen_55_inch   CGSizeEqualToSize([UIScreen mainScreen].bounds.size, CGSizeMake(414, 736))

//不同屏幕尺寸字体适配(320,568是因为效果图为IPHONE5 如果不是则根据实际情况修改)
#define kScreenWidthRatio  (Main_Screen_Width / 320.0)
#define kScreenHeightRatio (Main_Screen_Height / 568.0)
#define AdaptedWidth(x)  ceilf((x) * kScreenWidthRatio)
#define AdaptedHeight(x) ceilf((x) * kScreenHeightRatio)
#define AdaptedFontSize(R)     CHINESE_SYSTEM(AdaptedWidth(R))

// 字体大小(常规/粗体)
#define BOLDSYSTEMFONT(FONTSIZE)[UIFont boldSystemFontOfSize:FONTSIZE]
#define SYSTEMFONT(FONTSIZE)    [UIFont systemFontOfSize:FONTSIZE]
#define FONT(NAME, FONTSIZE)    [UIFont fontWithName:(NAME) size:(FONTSIZE)]
#define kRZBoldFont(x) [UIFont fontWithName:@"PingFangSC-Semibold" size: x]
#define kRZFont(x)     [UIFont fontWithName:@"PingFangSC-Regular"  size: x]

//中文字体
#define CHINESE_FONT_NAME  @"Heiti SC"
#define CHINESE_SYSTEM(x) [UIFont fontWithName:CHINESE_FONT_NAME size:x]

//重写NSLog,Debug模式下打印日志和当前行数
#if DEBUG

#define RZLog(FORMAT, ...) do {                                     \
fprintf(stderr,"\nfunction:%s \nline:%d content: -> %s\n",          \
__FUNCTION__,                                                       \
__LINE__,                                                           \
[[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);    \
} while (0)

#else
#define RZLog(FORMAT, ...) nil
#endif

/** 系统版本 */
#define FSystemVersion  ([[[UIDevice currentDevice] systemVersion] floatValue])
    #define DSystemVersion  ([[[UIDevice currentDevice] systemVersion] doubleValue])
#define SSystemVersion  ([[UIDevice currentDevice] systemVersion])

#define ios7_or_later ([UIDevice currentDevice].systemVersion.floatValue >= 7.0)
#define ios8_or_later ([UIDevice currentDevice].systemVersion.floatValue >= 8.0)
#define ios9_or_later ([UIDevice currentDevice].systemVersion.floatValue >= 9.0)

/** 当前app信息 */
#define kbundelId [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"]
#define kexecutable  [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleExecutable"]
#define kdisplayName  [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"]

/** 应用的Verison号 */
#define kappVersion [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]

/** build号 */
#define kappBuild [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]

/** AppDelegate对象 */
#define AppDelegateInstance [[UIApplication sharedApplication] delegate]

//获取图片资源
#define GetImage(imageName) [UIImage imageNamed:[NSString stringWithFormat:@"%@",imageName]]

//Library/Caches 文件路径
#define FilePath ([[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil])
//获取沙盒Document路径
#define kDocumentPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]
//获取沙盒temp路径
#define kTempPath NSTemporaryDirectory()
//获取沙盒Cache路径
#define kCachePath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]

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

#if TARGET_IPHONE_SIMULATOR
//模拟器
#endif

//NSUserDefaults 实例化
/**  以key,value存储信息 */
#define USERDEFAULTSET(key,value) [[NSUserDefaults standardUserDefaults] setObject:value forKey:key]
/** 以key取出value */
#define USERDEFAULTS(key) [[NSUserDefaults standardUserDefaults] objectForKey:key]
/** 以key删除value */
#define USERDEFAULTREMOVE(key) [[NSUserDefaults standardUserDefaults] removeObjectForKey:key]
/** 立即同步 */
#define USERDEFAULTSYNCHRONIZE  [[NSUserDefaults standardUserDefaults] synchronize]

/** 是否是iPad */
#define isPad  (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
/** 判断是否为iPhone */
#define isIPhone (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
  • 颜色宏
/** 三原色 */
#define UIColorRGBA(_r, _g, _b, _a) [UIColor colorWithRed:_r/255.f green:_g/255.f blue:_b/255.f alpha:_a]
#define UIColorRgb(_r, _g, _b) UIColorRGBA(_r, _g, _b, 1.0f)

/** 传入色值 */
#define LFHEXCOLOR_a(hex,a) [UIColor colorWithRed:((float)((hex & 0xFF0000) >> 16)) / 255.0 green:((float)((hex & 0xFF00) >> 8)) / 255.0 blue:((float)(hex & 0xFF)) / 255.0 alpha:(a)]
#define LFHEXCOLOR(hex) [UIColor colorWithRed:((float)((hex & 0xFF0000) >> 16)) / 255.0 green:((float)((hex & 0xFF00) >> 8)) / 255.0 blue:((float)(hex & 0xFF)) / 255.0 alpha:1]

/** 随机色  */
#define LFRandomColor UIColorRgb(arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256))

/** 背景色 */
#define BACKGROUND_COLOR [UIColor colorWithRed:242.0/255.0 green:236.0/255.0 blue:231.0/255.0 alpha:1.0]

/** 透明背景色 */
#define CLEARCOLOR [UIColor clearColor]
/*! navi蓝色 */
#define RZ_NaviBgBlueColor     RZ_COLOR(92, 177, 251, 1.0)
#define RZ_BGGrayColor         RZ_COLOR(239, 239, 239, 1.0)
#define RZ_TEXTGrayColor       RZ_COLOR(148, 147, 133, 1.0)
#define RZ_BLUEColor           RZ_COLOR(78, 164, 255, 1.0)
#define RZ_BGClearColor        [UIColor colorWithRed:0.1f green:0.1f blue:0.1f alpha:0.7f]

/*! 主题浅绿 */
#define RZ_Them_greenColor     RZ_COLOR(30, 198, 181, 1.0)

/*! 白色 */
#define RZ_White_Color         [UIColor whiteColor]

/*! 红色 */
#define RZ_Red_Color           [UIColor redColor]

/*! 黄色 */
#define RZ_Yellow_Color        [UIColor yellowColor]

/*! 绿色 */
#define RZ_Green_Color         [UIColor greenColor]

/*! 蓝色 */
#define RZ_Blue_Color          [UIColor blueColor]

/*! 无色 */
#define RZ_Clear_Color         [UIColor clearColor]

/*! 橙色 */
#define RZ_Orange_Color        [UIColor orangeColor]

/*! 黑色 */
#define RZ_Black_Color         [UIColor blackColor]

/*! 浅灰色色 */
#define RZ_LightGray_Color     [UIColor lightGrayColor]

  • 常量,地址,三方key都可以写成宏
/*! 常量 */
static NSString* const kBase_URL=@"www.baidu.com";
  • iOS 11 适配
#define kAdjustmentBehavior(VC, view) if (@available(iOS 11.0, *)) {                \
    view.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;  \
} else {                                                                            \
    VC.automaticallyAdjustsScrollViewInsets = NO;                                   \
}                                                                                   \
  • 线程队列
/*! 主线程同步队列 */
#define dispatch_main_sync_safe(block)          \
if ([NSThread isMainThread]) {                  \
block();                                        \
} else {                                        \
dispatch_sync(dispatch_get_main_queue(), block);\
}
/*! 主线程异步队列 */
#define dispatch_main_async_safe(block)        \
if ([NSThread isMainThread]) {                 \
block();                                       \
} else {                                       \
dispatch_async(dispatch_get_main_queue(), block);\
}

以下是引用的一些宏

//字符串是否为空
#define kStringIsEmpty(str) ([str isKindOfClass:[NSNull class]] || str == nil || [str length] < 1 ? YES : NO )
//数组是否为空 
#define kArrayIsEmpty(array) (array == nil || [array isKindOfClass:[NSNull class]] || array.count == 0)
//字典是否为空  
#define kDictIsEmpty(dic) (dic == nil || [dic isKindOfClass:[NSNull class]] || dic.allKeys == 0)
//是否是空对象
#define kObjectIsEmpty(_object) (_object == nil \
|| [_object isKindOfClass:[NSNull class]] \
|| ([_object respondsToSelector:@selector(length)] && [(NSData *)_object length] == 0) \
|| ([_object respondsToSelector:@selector(count)] && [(NSArray *)_object count] == 0))

//一些缩写
#define kApplication [UIApplication sharedApplication]
#define kKeyWindow [UIApplication sharedApplication].keyWindow
#define kAppDelegate [UIApplication sharedApplication].delegate
#define kUserDefaults [NSUserDefaults standardUserDefaults]
#define kNotificationCenter [NSNotificationCenter defaultCenter]

/** 当前语言 */
#define CurrentLanguage ([[NSLocale preferredLanguages] objectAtIndex:0])

//获取一段时间间隔
#define kStartTime CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
#define kEndTime   NSLog(@"Time: %f", CFAbsoluteTimeGetCurrent() - start)

//弱引用/强引用
#define kWeakSelf(type)   __weak typeof(type) weak##type = type;
#define kStrongSelf(type) __strong typeof(type) type = weak##type;

/*! 复制文字内容 */
#define BAKit_CopyContent(content) [[UIPasteboard generalPasteboard] setString:content]

//上传图片相关
#define kImageCollectionCell_Width floorf((Main_Screen_Width - 10*2- 10*3)/3)
//最大的上传图片张数
#define kupdateMaximumNumberOfImage 12

//由角度转换弧度
#define kDegreesToRadian(x)      (M_PI * (x) / 180.0)
//由弧度转换角度
#define kRadianToDegrees(radian) (radian * 180.0) / (M_PI)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容