iOS常用宏定義大全

宏定義與常量的區(qū)別

宏:只是在預(yù)處理器里進(jìn)行文本替換,不做任何類型檢查,宏能定義代碼,const不能,多個宏編譯時間相對較長,影響開發(fā)效率,調(diào)試過慢,const只會編譯一次,縮短編譯時間。
所以在使用的時候,最好把代碼和一些基本數(shù)據(jù)類型如int抽成宏。
而對于常量字符串使用const,蘋果也是這樣使用的。

下面總結(jié)一下一些常用的宏定義。
1.獲取主屏幕和屏幕寬度與高度

OC

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

Swift

let SCREEN_WIDTH = UIScreen.mainScreen().bounds.width
let SCREENH_HEIGHT = UIScreen.mainScreen().bounds.height
let MAIN_SCREEN = UIScreen.mainScreen()

如果支持橫屏可以用下面的宏:
OC

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000 // 當(dāng)前Xcode支持iOS8及以上
#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

Swift



 #if (__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000  // 當(dāng)前Xcode支持iOS8及以上
let SCREEN_WIDTH = (MAIN_SCREEN.respondsToSelector(#selector(UIScreen.nativeBounds)) ? MAIN_SCREEN.nativeBounds.width/MAIN_SCREEN.nativeScale : MAIN_SCREEN.bounds.width)
let SCREENH_HEIGHT = (MAIN_SCREEN.respondsToSelector(#selector(UIScreen.nativeBounds)) ? MAIN_SCREEN.nativeBounds.height/MAIN_SCREEN.nativeScale : MAIN_SCREEN.bounds.height)
let SCREEN_SIZE = (MAIN_SCREEN.respondsToSelector(#selector(UIScreen.nativeBounds)) ? CGSizeMake(SCREEN_WIDTH, SCREENH_HEIGHT) : MAIN_SCREEN.bounds.size)
#else
let SCREEN_WIDTH = UIScreen.mainScreen().bounds.width
let SCREENH_HEIGHT = UIScreen.mainScreen().bounds.height
let SCREEN_SIZE = UIScreen.mainScreen().bounds.size
#endif

2.獲取通知中心和UserDefaults

OC

#define DENotificationCenter [NSNotificationCenter defaultCenter]
#define SDUserDefaults [NSUserDefaults standardUserDefaults]

Swift

let DENotificationCenter = NSNotificationCenter.defaultCenter()
let SDUserDefaults = NSUserDefaults.standardUserDefaults()

3.設(shè)置隨機(jī)顏色

OC

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

Swift

let GRandomColor = UIColor(red: CGFloat(arc4random_uniform(256)/255), green: CGFloat(arc4random_uniform(256)/255), blue: CGFloat(arc4random_uniform(256)/255), alpha: 1)

4.設(shè)置RGB顏色/設(shè)置RGBA顏色

OC

#define RGBColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]
#define RGBAColor(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(r)/255.0 blue:(r)/255.0 alpha:a]
// clear背景顏色
#define GClearColor [UIColor clearColor]

Swift

func colorWith(red red : CGFloat,green : CGFloat,blue:CGFloat) -> UIColor {
    return UIColor(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: 1)
}

func colorWith(red red : CGFloat,green : CGFloat,blue:CGFloat,a:CGFloat) -> UIColor {
    return UIColor(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: a)
}

5.自定義高效率的 NSLog

項(xiàng)目開發(fā)中,我們會在許多地方加上Log,但是發(fā)布的時候又不想用這些Log,我們也不可能一個一個的刪除,所以自定義Log是必然的!
OC

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

Swift

func debugLog<T>(message: T,
              file: String = #file,
              method: String = #function,
              line: Int = #line)
{
    #if DEBUG
    print("\((file as NSString).lastPathComponent)[\(line)], \(method): \(message)")
    #endif
}

6.弱引用/強(qiáng)引用

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

7.由角度轉(zhuǎn)換弧度 由弧度轉(zhuǎn)換角度

#define RadianFrom(degree) (M_PI * (degree) / 180.0)
#define DegreeFrom(radian) (radian*180.0)/(M_PI)

8.獲取UIImage

#define GUIImageFor(imageName) [UIImage imageNamed:[NSString stringWithFormat:@"%@",imageName]]

9.獲取當(dāng)前語言

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

10.使用 ARC 和 MRC

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

11.判斷當(dāng)前的iPhone設(shè)備/系統(tǒng)版本

OC

//判斷是否為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
//獲取系統(tǒng)版本
#define IOS_SYSTEM_VERSION [[[UIDevice currentDevice] systemVersion] floatValue]
//判斷 iOS 8 或更高的系統(tǒng)版本
#define IOS_VERSION_8_OR_LATER (([[[UIDevice currentDevice] systemVersion] floatValue] >=8.0)? (YES):(NO))

Swift



//判斷是否為iPhone
let IS_IPHONE = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Phone)
//判斷是否為iPad
let IS_IPAD = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad)
//判斷是否為ipod
let IS_IPOD = (UIDevice.currentDevice().model == "iPod touch")
// 判斷是否為 iPhone 5SE
let is_iPhone5SE = (UIScreen.mainScreen().bounds.width == 320.0 && UIScreen.mainScreen().bounds.height == 568.0)
// 判斷是否為iPhone 6/6s
let is_iPhone6Or6s = (UIScreen.mainScreen().bounds.width == 375.0 && UIScreen.mainScreen().bounds.height == 667.0)
// 判斷是否為iPhone 6Plus/6sPlus
let is_iPhone6PlusOr6sPlus = (UIScreen.mainScreen().bounds.width == 414.0 && UIScreen.mainScreen().bounds.height == 736.0)
//獲取系統(tǒng)版本
let IOS_SYSTEM_VERSION = Float(UIDevice.currentDevice().systemVersion)!
//判斷 iOS 8 或更高的系統(tǒng)版本
let IS_IOS_VERSION_8_OR_LATER = ((IOS_SYSTEM_VERSION >= 8.0) ? (true):(false))

12.判斷是真機(jī)還是模擬器

#if TARGET_OS_IPHONE
//iPhone Device
#endif
#if TARGET_IPHONE_SIMULATOR
//iPhone Simulator

#endif

13.沙盒目錄文件

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

14.GCD
OC

//GCD - 只執(zhí)行一次
#define kDISPATCH_ONCE(onceBlock) static dispatch_once_t onceToken; dispatch_once(&onceToken, onceBlock);
//GCD - 在Main線程上運(yùn)行
#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);

Swift

func kDISPATCH_ONCE(onceBlock : dispatch_block_t) {
    var onceToken = dispatch_once_t()
    dispatch_once(&onceToken, onceBlock)
}

func kDISPATCH_MAIN_THREAD(mainQueueBlock : dispatch_block_t) {
    dispatch_async(dispatch_get_main_queue(), mainQueueBlock)
}

鍵值提示

#define GKeyPath(objc,keyPath) @(((void)objc.keyPath,#keyPath))

//棄用的方法后綴

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

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

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