iOS (OC/Swift)開發(fā)常用的宏定義(日記)

OC版本

//獲取屏幕的寬、高
#define KScreenWidth [UIScreen mainScreen].bounds.size.width
#define KScreenHeight [UIScreen mainScreen].bounds.size.height

// __block
#define kBlcokSelf(pSelf) __block typeof(&*self) pBlcokSelf = self

//狀態(tài)欄的高度
#ifdef __IPHONE_13_0 //判斷是否是13以上系統(tǒng)
#define statusBarHeight [[UIApplication sharedApplication] windows].firstObject.windowScene.statusBarManager.statusBarFrame.size.height
#else
#define statusBarHeight [[UIApplication sharedApplication] statusBarFrame].size.height
#endif

//狀態(tài)欄+導航欄高度
#define NavAndstatusBarHeight (statusBarHeight+44)
//判斷是否是劉海屏
#define iPhoneX ((statusBarHeight != 20) ? YES : NO)
//底部安全距離
#define bottomLayoutIPhoneX (iPhoneX ? 34 : 0)

//判斷手機屏幕尺寸
//3.5寸屏幕
#define ThreePointFiveInch ([UIScreen mainScreen].bounds.size.height == 480.0)
//4.0寸屏幕(iPhone SE)
#define FourInch ([UIScreen mainScreen].bounds.size.height == 568.0)
//4.7寸屏幕(iPhone 6/6s/7/8/SE2)
#define FourPointSevenInch ([UIScreen mainScreen].bounds.size.height == 667.0)
//5.4寸屏幕(iPhone 12 mini/13 mini)
#define FivePointFourSevenInch ([UIScreen mainScreen].bounds.size.height == 780.0)
//5.5寸屏幕(iPhone 6p/7p/8p)
#define FivePointFiveSevenInch ([UIScreen mainScreen].bounds.size.height == 736.0)
//5.8寸屏幕(iPhone x/xs/11Pro)
#define FivePointEightSevenInch ([UIScreen mainScreen].bounds.size.height == 812.0)
//6.1(iPhone xr/11/12/12 Pro/13/13 Pro/14/14Pro)
#define SixPointOneSevenInch (([UIScreen mainScreen].bounds.size.height == 896.0 && [UIScreen mainScreen].scale == 2) || [UIScreen mainScreen].bounds.size.height == 844.0 || [UIScreen mainScreen].bounds.size.height == 852.0)
//6.5寸屏幕(iPhone xsMax/11ProMax)
#define SixPointFiveSevenInch ([UIScreen mainScreen].bounds.size.height == 896.0 && [UIScreen mainScreen].scale == 3)
//6.7寸屏幕(iPhone 12 Pro Max/13 Pro Max/14Plus/14ProMax)
#define SixPointSevenSevenInch ([UIScreen mainScreen].bounds.size.height == 926.0 || [UIScreen mainScreen].bounds.size.height == 932)

//判斷是否從右往左讀?。≧TL,阿拉伯語是RTL)這里只適配了阿拉伯語
#define isRTL [[NSLocale preferredLanguages].firstObject hasPrefix:@"ar-"]

//設置顏色
#define HexRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
#define HexRGBAlpha(rgbValue,a) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:(a)]

//GCD (子線程、主線程定義)
#define BACK(block) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block)
#define MAIN(block) dispatch_async(dispatch_get_main_queue(),block)

// 獲取版本號
#define LOCAL_RELEASE_VERSION [[NSBundle mainBundle]infoDictionary][@"CFBundleShortVersionString"]

// 獲取手機型號
#define Phone_Model [[UIDevice currentDevice] model]

// 系統(tǒng)版本號
#define System_Version [[UIDevice currentDevice] systemVersion]
//設置本地圖片
#define TL_IMAGE(name) [UIImage imageNamed:name]

Swift版本

//獲取屏幕高寬
let ScreenWith = UIScreen.main.bounds.size.width
let ScreenHeight = UIScreen.main.bounds.size.height

//返回狀態(tài)欄高度
#if __IPHONE_13_0
let statusBarHeight = UIApplication.shared.windows.first?.windowScene?.statusBarManager?.statusBarFrame.size.height
#else
let statusBarHeight = UIApplication.shared.statusBarFrame.size.height
#endif

//返回狀態(tài)欄和導航欄的高度
let NavAndstatusBarHeight = statusBarHeight + 44

//判斷是否是劉海屏
let iphoneX = ((statusBarHeight != 20) ? true : false)

// 獲取版本號
let LOCAL_RELEASE_VERSION = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String

// 獲取手機型號
let Phone_Model = UIDevice.current.model

// 系統(tǒng)版本號
let System_Version = UIDevice.current.systemVersion

//獲取當前語言
let Language_first_local = NSLocale.preferredLanguages.first!


//GCD(進入異步線程)
func GCDThread (completion: (() -> Void)? = nil) {
    DispatchQueue.global(qos: .default).async {
        completion!()
    }
}
//回到主線程
func MainThread (completion: (() -> Void)? = nil) {
    DispatchQueue.main.async {
        completion!()
    }
}
//延遲執(zhí)行
func AfterGCD (timeInval:CGFloat, completion: (() -> Void)? = nil) {
    DispatchQueue.main.asyncAfter(deadline: .now() + timeInval) {
        completion!()
    }
}


// MARK: - 顏色
var RGBA:(NSInteger, NSInteger, NSInteger, CGFloat) -> UIColor = { (r,g,b,a) in
    return UIColor(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: a)
}

var RGB:(NSInteger, NSInteger, NSInteger) -> UIColor = { (r,g,b) in
    return UIColor(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: 1.0)
}
//隨機顏色
let RANDOM_COLOR = RGB(Int(arc4random())%255, Int(arc4random())%255, Int(arc4random())%255)

//16進制顏色轉換
var HexRGB:(NSInteger) -> UIColor = { hex in
    return UIColor(red: ((CGFloat)((hex & 0xFF0000) >> 16)) / 255.0, green: ((CGFloat)((hex & 0xFF00) >> 8)) / 255.0, blue: ((CGFloat)((hex & 0xFF))) / 255.0, alpha: 1.0)
}
//16進制顏色轉換(帶透明度)
var HexRGBAlpha:(NSInteger, CGFloat) -> UIColor = { (hex, alpha) in
    return UIColor(red: ((CGFloat)((hex & 0xFF0000) >> 16)) / 255.0, green: ((CGFloat)((hex & 0xFF00) >> 8)) / 255.0, blue: ((CGFloat)((hex & 0xFF))) / 255.0, alpha: alpha)
}

//storyboard
var Storyboard_INSTANT_VC_WITH_ID:(String, String) -> UIViewController = { name,identifier in
    return UIStoryboard.init(name: name, bundle: nil).instantiateViewController(withIdentifier: identifier)
}

//nib
var Nib_INSTANT_WITH_NAME:(String) -> Any? = { name in
    return Bundle.main.loadNibNamed(name, owner: nil, options: nil)?.first
}


//設置本地圖片
var imageName:(String) -> UIImage = { imgName in
    return UIImage(named: imgName)!
}


/// 判斷設備是 iPhone
let isIPhone = UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.phone

/// 判斷設備是 iPad
let isIPad = UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad

/// 判斷是否是橫屏
public func isIsLandscape() -> Bool {
    return UIDevice.current.orientation.isLandscape || UIApplication.shared.statusBarOrientation == UIInterfaceOrientation.landscapeLeft  || UIApplication.shared.statusBarOrientation == UIInterfaceOrientation.landscapeRight
}

///獲取keywindow
#if __IPHONE_13_0
let KeyWindows = UIApplication.shared.windows.first
#else
let KeyWindows = UIApplication.shared.keyWindow
#endif

///獲取Document路徑
let DocumentPath_Local = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "/"

///獲取caches路徑
let CachesPath_Local = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! + "/"

///獲取caches路徑
let LibraryPath_Local = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first! + "/"

///獲取temp路徑
let TempPath_Local = NSTemporaryDirectory()


///打印log
func printLog(_ items: Any..., separator: String = " ", terminator: String = "\n") {
#if DEBUG
    let currentDate = Date()
    let calendar = Calendar.current
    let components = calendar.dateComponents([.nanosecond], from: currentDate)
    let nanosecond = components.nanosecond ?? 000
    // 由于 DateComponents 的 nanosecond 是以納秒為單位,我們需要將其轉換為毫秒
    let milliseconds = nanosecond/1000000
    let paddedNumber = String(format: "%03d", milliseconds)

    let dateformatter = DateFormatter()
    dateformatter.dateFormat = "YYYY-MM-dd HH:mm:ss"http:// 自定義時間格式
    let time = dateformatter.string(from: currentDate)

    print("\(time) \(paddedNumber):", terminator:"")
    print(items, separator: separator, terminator: terminator)
//    print("當前是Debug模式")
#else
//    print("當前不是Debug模式")
#endif
}

/// 添加通知
/// - Parameters:
///   - name: 通知名稱
///   - object: 傳遞的參數(shù)
func NotificationCenterPost(name:String, object:Any? = nil) {
    NotificationCenter.default.post(name: NSNotification.Name(name), object: object)
}


/// 接收通知
/// - Parameters:
///   - name: 通知名稱
///   - isMainThread: 是否在主線程
///   - completion: 通知執(zhí)行的方法
func NotificationCenterAdd(name:String, isMainThread:Bool = true, completion:@escaping (Notification) -> Void) {
    NotificationCenter.default.addObserver(forName: NSNotification.Name(name), object: nil, queue: (isMainThread ? .main : .current)) { not in
        completion(not)
    }
}


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

相關閱讀更多精彩內容

友情鏈接更多精彩內容