我在iOS項目中常用的宏,提高不少效率,持續(xù)更新。。。

在項目中合理的使用一些宏,可以很大的提高代碼效率,代碼簡潔度!下面我就列舉一些我常用的宏,隨著項目的進行,我會持續(xù)更新!

在這里呢,我一般是把常用宏分類寫:基礎(chǔ)宏,顏色宏,地址宏,通知文字等常量

  • 基礎(chǔ)宏
/** MainScreen bounds */ 
#define Main_Screen_Bounds [[UIScreen mainScreen] bounds]
/** 屏幕寬高 */
#define kScreeWith [UIScreen mainScreen].bounds.size.width
#define kScreeHeight [UIScreen mainScreen].bounds.size.height

/** 狀態(tài)欄的高度 */
/** 在iPhone x以前蘋果手機的各機型狀態(tài)欄高度均為20;
在iPhone x以后蘋果新推出劉海屏機型,蘋果的各機型狀態(tài)欄高度均為44。
但是今年蘋果隨著蘋果新操作系統(tǒng)iOS 14的推出導(dǎo)致了iPhone x以后的部分蘋果劉海屏機型狀態(tài)欄的高度的改變有的為47,有的為48,有的還是44。
目前這個更改不知道是ios 14.2的bug,還是說以后蘋果會把劉海屏機型的狀態(tài)欄的高度依然全部改成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
// 獲取狀態(tài)欄高度
+ (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;
}

// 導(dǎo)航欄高度(custom=44)+狀態(tài)欄高度
// #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 如果不是則根據(jù)實際情況修改)
#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))

// 字體大小(常規(guī)/粗體)
#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模式下打印日志和當(dāng)前行數(shù)
#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

/** 系統(tǒng)版本 */
#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)

/** 當(dāng)前app信息 */
#define kbundelId [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"]
#define kexecutable  [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleExecutable"]
#define kdisplayName  [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"]

/** 應(yīng)用的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 )
//數(shù)組是否為空 
#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]

/** 當(dāng)前語言 */
#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;

/*! 復(fù)制文字內(nèi)容 */
#define BAKit_CopyContent(content) [[UIPasteboard generalPasteboard] setString:content]

//上傳圖片相關(guān)
#define kImageCollectionCell_Width floorf((Main_Screen_Width - 10*2- 10*3)/3)
//最大的上傳圖片張數(shù)
#define kupdateMaximumNumberOfImage 12

//由角度轉(zhuǎn)換弧度
#define kDegreesToRadian(x)      (M_PI * (x) / 180.0)
//由弧度轉(zhuǎn)換角度
#define kRadianToDegrees(radian) (radian * 180.0) / (M_PI)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容