您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

iOS 日常開發:常用巨集定義大全

編輯:iOS 開發基礎

授權轉載,作者:判若兩人丶(GitHub)

前言:

工作中,很多夥伴都習慣在 PCH 檔裡定義一批常用巨集,但往往卡在兩件事上:一是覺得為這些「小東西」花時間不值得,二是隔一陣子就忘了怎麼寫。我自己也一樣,乾脆把日常累積的常用巨集整理成一份清單分享出來,可以直接複製進專案使用(內容持續更新)。

為了方便取用,請點擊:GitHub - 巨集定義標頭檔下載

1. 取得螢幕寬高

#define SCREEN_WIDTH   [UIScreen mainScreen].bounds.size.width
#define SCREENH_HEIGHT [UIScreen mainScreen].bounds.size.height

依一位網友的提醒,如果需要支援橫向旋轉,可以用下面這組寫法:

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000  // 當前 Xcode 支援 iOS 8 及以上
#define SCREEN_WIDTH ([[UIScreen mainScreen] respondsToSelector:@selector(nativeBounds)] ? [UIScreen mainScreen].nativeBounds.size.width/[UIScreen mainScreen].nativeScale : [UIScreen mainScreen].bounds.size.width)
#define SCREENH_HEIGHT ([[UIScreen mainScreen] respondsToSelector:@selector(nativeBounds)] ? [UIScreen mainScreen].nativeBounds.size.height/[UIScreen mainScreen].nativeScale : [UIScreen mainScreen].bounds.size.height)
#define SCREEN_SIZE ([[UIScreen mainScreen] respondsToSelector:@selector(nativeBounds)] ? CGSizeMake([UIScreen mainScreen].nativeBounds.size.width/[UIScreen mainScreen].nativeScale, [UIScreen mainScreen].nativeBounds.size.height/[UIScreen mainScreen].nativeScale) : [UIScreen mainScreen].bounds.size)
#else
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREENH_HEIGHT [UIScreen mainScreen].bounds.size.height
#define SCREEN_SIZE [UIScreen mainScreen].bounds.size
#endif

2. 取得通知中心

#define LRNotificationCenter [NSNotificationCenter defaultCenter]

3. 隨機顏色

#define LRRandomColor [UIColor colorWithRed:arc4random_uniform(256)/255.0 green:arc4random_uniform(256)/255.0 blue:arc4random_uniform(256)/255.0 alpha:1.0]

4. RGB/RGBA 顏色

#define LRRGBColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]
#define LRRGBAColor(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(r)/255.0 blue:(r)/255.0 alpha:a]
// 清除背景顏色
#define LRClearColor [UIColor clearColor]

5. 自訂高效率的 NSLog

專案裡到處都會需要打 Log,但發布時又不希望這些 Log 存在,也不可能逐條刪除,因此自訂一個 Log 巨集是必然要做的事。

#ifdef DEBUG
#define LRLog(...) NSLog(@"%s 第%d行 \n %@\n\n", __func__, __LINE__, [NSString stringWithFormat:__VA_ARGS__])
#else
#define LRLog(...)
#endif

6. 弱引用/強引用

#define LRWeakSelf(type)  __weak typeof(type) weak##type = type;
#define LRStrongSelf(type)  __strong typeof(type) type = weak##type;

第二種用法:定義好弱引用巨集之後,直接敲 weak 就能觸發程式碼片段提示。

7. 設定 view 圓角與邊框

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

8. 角度與弧度互轉

#define LRDegreesToRadian(x) (M_PI * (x) / 180.0)
#define LRRadianToDegrees(radian) ((radian)*180.0)/(M_PI)

9. 載入提示框(Toast)

這個巨集很好用,但需要先用 CocoaPods 引入第三方庫 Toast。使用方式:

LRToast(@"網絡加載失敗");
#define LRToast(str)  CSToastStyle *style = [[CSToastStyle alloc] initWithDefaultStyle];\
[kWindow  makeToast:str duration:0.6 position:CSToastPositionCenter style:style];\
kWindow.userInteractionEnabled = NO;\
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{\
kWindow.userInteractionEnabled = YES;\
});\

10. 載入提示框(MBProgressHUD)

這組巨集與上一個概念類似。

// 加載
#define kShowNetworkActivityIndicator() [UIApplication sharedApplication].networkActivityIndicatorVisible = YES
// 收起加載
#define HideNetworkActivityIndicator()      [UIApplication sharedApplication].networkActivityIndicatorVisible = NO
// 設置加載
#define NetworkActivityIndicatorVisible(x)  [UIApplication sharedApplication].networkActivityIndicatorVisible = x
#define kWindow [UIApplication sharedApplication].keyWindow
#define kBackView        for (UIView *item in kWindow.subviews) {\
if (item.tag == 10000) {\
[item removeFromSuperview];\
UIView * aView = [[UIView alloc] init];\
aView.frame = [UIScreen mainScreen].bounds;\
aView.tag = 10000;\
aView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];\
[kWindow addSubview:aView];\
}\
}
#define kShowHUDAndActivity kBackView; [MBProgressHUD showHUDAddedTo:kWindow animated:YES]; kShowNetworkActivityIndicator()
#define kHiddenHUD [MBProgressHUD hideAllHUDsForView:kWindow animated:YES]
#define kRemoveBackView      for (UIView *item in kWindow.subviews) {\
if (item.tag == 10000) {\
[UIView animateWithDuration:0.4 animations:^{\
item.alpha = 0.0;\
} completion:^(BOOL finished) {\
[item removeFromSuperview];\
}];\
}\
}
#define kHiddenHUDAndAvtivity kRemoveBackView; kHiddenHUD; HideNetworkActivityIndicator()

11. 取得 view 的 frame 與圖片資源

// 獲取 view 的 frame(不建議使用)
// #define kGetViewWidth(view)  view.frame.size.width
// #define kGetViewHeight(view) view.frame.size.height
// #define kGetViewX(view)      view.frame.origin.x
// #define kGetViewY(view)      view.frame.origin.y
// 獲取圖片資源
#define kGetImage(imageName) [UIImage imageNamed:[NSString stringWithFormat:@"%@", imageName]]

12. 取得當前語言

#define LRCurrentLanguage ([[NSLocale preferredLanguages] objectAtIndex:0])

13. 判斷 ARC 與 MRC

#if __has_feature(objc_arc)
// ARC
#else
// MRC
#endif

14. 判斷裝置與系統版本

// 判斷是否為 iPhone
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
// 判斷是否為 iPad
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
// 判斷是否為 iPod
#define IS_IPOD ([[[UIDevice currentDevice] model] isEqualToString:@"iPod touch"])
// 判斷是否為 iPhone 5SE
#define iPhone5SE [[UIScreen mainScreen] bounds].size.width == 320.0f && [[UIScreen mainScreen] bounds].size.height == 568.0f
// 判斷是否為 iPhone 6/6s
#define iPhone6_6s [[UIScreen mainScreen] bounds].size.width == 375.0f && [[UIScreen mainScreen] bounds].size.height == 667.0f
// 判斷是否為 iPhone 6Plus/6sPlus
#define iPhone6Plus_6sPlus [[UIScreen mainScreen] bounds].size.width == 414.0f && [[UIScreen mainScreen] bounds].size.height == 736.0f
// 獲取系統版本
#define IOS_SYSTEM_VERSION [[[UIDevice currentDevice] systemVersion] floatValue]
// 判斷 iOS 8 或更高版本
#define IOS_VERSION_8_OR_LATER ([[[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) ? (YES) : (NO)

15. 判斷真機或模擬器

#if TARGET_OS_IPHONE // 真機
#endif
#if TARGET_IPHONE_SIMULATOR // 模擬器
#endif

16. 沙盒目錄

// 獲取 temp
#define kPathTemp NSTemporaryDirectory()
// 獲取沙盒 Document
#define kPathDocument [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]
// 獲取沙盒 Cache
#define kPathCache [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]

17. GCD 相關巨集

很多人嫌 GCD 的樣板程式碼冗長,包成巨集之後乾淨不少。

// GCD - 一次性執行
#define kDISPATCH_ONCE_BLOCK(onceBlock) static dispatch_once_t onceToken; dispatch_once(&onceToken, onceBlock);
// GCD - 在 Main 執行緒執行
#define kDISPATCH_MAIN_THREAD(mainQueueBlock) dispatch_async(dispatch_get_main_queue(), mainQueueBlock);
// GCD - 開啟非同步執行緒
#define kDISPATCH_GLOBAL_QUEUE_DEFAULT(globalQueueBlock) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), globalQueueBlocl);

巨集與 const 該怎麼選

不少人在定義常數字串(最典型的就是伺服器位址)時習慣用巨集。但其實這種情境更應該改用 const。理由如下:

  • 巨集的用法:一般字串抽成巨集、程式碼片段抽成巨集。

  • const 的用法:常用字串定義成 const(對於常數字串,蘋果建議使用 const)。

兩者的差異:

1. 處理時機不同:巨集屬於前置編譯階段,const 屬於編譯階段。

2. 巨集可以定義程式碼片段,const 不行;大量巨集會拖長編譯時間、影響開發效率與除錯速度,而 const 只會編譯一次,編譯時間更短。

3. 巨集不會做型別檢查,const 會。

結論很清楚:定義常數字串就用 const,需要封裝程式碼片段就用巨集。實際專案中的 const 用法如下圖。

上圖只是簡單定義了幾個常數字串。做法是先建立一個類別,在 .h 與 .m 中引入 <Foundation/Foundation.h>,於 .h 宣告字串、在 .m 中實作,最後把這個類別加入 PCH 檔,就能在專案任何角落自由取用了。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved