iOS开发开发自用宏定义

96
WangK_Dev
0.4 2017.07.27 14:43* 字数 312

一个小伙伴在问我自己经常用的宏定义,就记录下来,以后如果有新的再补充,目前已经很顺手了。
宏是全局的,既然是全局的就可能会造成冲突!所以我们在定义自己宏的时候,尽量有特色,不要跟系统的冲突了。
关于宏的使用,个人见仁见智吧,有些公司是不让用宏的,有些为了提高开发效率让试用,这个 不好说谁对谁错。。。。

常用代码使用部分


#pragma mark ------------------1.框架使用宏定义---------------------
//masonry的全局宏定义
// 定义这个常量,就可以不用在开发过程中使用"mas_"前缀。
#define MAS_SHORTHAND
// 定义这个常量,就可以让Masonry帮我们自动把基础数据类型的数据,自动装箱为对象类型。
#define MAS_SHORTHAND_GLOBALS

#pragma mark ------------------2.颜色宏定义---------------------
//自定义RGB颜色
#define WKRBGColor(r,g,b,a) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a]
//自定义十六进制颜色(使用需要有Color+HEX的扩展)
#define WKHEXColor(HexColor) [UIColor colorWithHexString:[NSString stringWithFormat:@"%@",HexColor]]

#define WKRGB16Color(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 WKRandomColor [UIColor colorWithRed:arc4random_uniform(256)/255.0 green:arc4random_uniform(256)/255.0 blue:arc4random_uniform(256)/255.0 alpha:1.0]
// rgb颜色转换(16进制转10进制)
#define WKColorFromRGB(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 WKFont(size) ([UIFont systemFontOfSize:ScaleWidth(size)])
#define WKBoldFont(size) ([UIFont boldSystemFontOfSize:ScaleHeigth(size)])

#pragma mark ------------------3.打印宏定义---------------------

#ifdef DEBUG
#define WKLog(format, ...) printf("\n[%s] %s [第%d行] %s\n", __TIME__, __FUNCTION__, __LINE__, [[NSString stringWithFormat:format, ## __VA_ARGS__] UTF8String]);
#else
#define WKLog(format, ...)
#endif
#pragma mark ------------------4.获取屏幕 宽度、高度  判断的支持横屏---------------------

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000 // 当前Xcode支持iOS8及以上
#define WKMainScreenBounds [UIScreen mainScreen].bounds

#define KSCREEN_WIDTH ([[UIScreen mainScreen] respondsToSelector:@selector(nativeBounds)]?[UIScreen mainScreen].nativeBounds.size.width/[UIScreen mainScreen].nativeScale:[UIScreen mainScreen].bounds.size.width)

#define KSCREEN_HEIGHT ([[UIScreen mainScreen] respondsToSelector:@selector(nativeBounds)]?[UIScreen mainScreen].nativeBounds.size.height/[UIScreen mainScreen].nativeScale:[UIScreen mainScreen].bounds.size.height)

#define kSCREENSIZE ([[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 KSCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define KSCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define kSCREENSIZE [UIScreen mainScreen].bounds.size
#endif

#pragma mark ------------------5.适配屏幕---------------------

#define ScaleWidth(width)           width/375.0*KSCREEN_WIDTH
#define ScaleHeigth(height)           height/667.0*KSCREEN_HEIGHT

#pragma mark ------------------6.系统相关---------------------
//APP版本号 build号 项目名称
#define  WKAPPVERSION  [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]
#define  WKAPPBUILD  [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]
#define  WKProjectName [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"]


// 获取当前系统版本
#define IOS_VERSION [[[UIDevice currentDevice] systemVersion] floatValue]
#define CurrentSystemVersion [[UIDevice currentDevice] systemVersion]
//判断是否是iOS7
#define IsIOS7 ([[[UIDevice currentDevice] systemVersion] floatValue] >=7.0 ? YES : NO)
//判断是真机还是模拟器
#if TARGET_OS_IPHONE
//iPhone Device
#endif

#if TARGET_IPHONE_SIMULATOR
//iPhone Simulator
#endif

//检查系统版本
#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)

#pragma mark ------------------7.图片---------------------
//读取本地图片
#define WKLOCALIMAGE(file,ext) [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:file ofType:ext]]
// UIImage对象
#define WKIMAGE(imageName) [UIImage imageNamed:[NSString stringWithFormat:@"%@",imageName]]


#pragma mark ------------------8.GCD---------------------

#define WKBACK(block) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block)
#define WKMAIN(block) dispatch_async(dispatch_get_main_queue(),block)
//GCD - 一次性执行
#define WKDISPATCH_ONCE_BLOCK(onceBlock) static dispatch_once_t onceToken; dispatch_once(&onceToken, onceBlock);
//GCD - 在Main线程上运行
#define WKDISPATCH_MAIN_THREAD(mainQueueBlock) dispatch_async(dispatch_get_main_queue(), mainQueueBlock);
//GCD - 开启异步线程
#define WKDISPATCH_GLOBAL_QUEUE_DEFAULT(globalQueueBlock) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), globalQueueBlocl);

#pragma mark --------------9.判断字符串、数组、字典 、对象 是否为空------------------

#define WKStringIsEmpty(str) ([str isKindOfClass:[NSNull class]] || str == nil || [str length] < 1 ? YES : NO )
#define WKArrayIsEmpty(array) (array == nil || [array isKindOfClass:[NSNull class]] || array.count == 0)
#define WKDictIsEmpty(dic) (dic == nil || [dic isKindOfClass:[NSNull class]] || dic.allKeys == 0)
#define WKObjectIsEmpty(_object) (_object == nil \
|| [_object isKindOfClass:[NSNull class]] \
|| ([_object respondsToSelector:@selector(length)] && [(NSData *)_object length] == 0) \
|| ([_object respondsToSelector:@selector(count)] && [(NSArray *)_object count] == 0))

#pragma mark --------------10.强引用 若引用------------------

#define WKWeakSelf(type)  __weak typeof(type) weak##type = type;
#define WKStrongSelf(type) __strong typeof(type) type = weak##type;

#pragma mark --------------11.NSUserDefaults  存/获得/删对象------------------

#define WKUserDefaults [NSUserDefaults standardUserDefaults]
//存储对象
#define WKUserDefaultSaveObjectForKey(__VALUE__,__KEY__) \
{\
[WKUserDefaults setObject:__VALUE__ forKey:__KEY__];\
[WKUserDefaults synchronize];\
}
//获得存储的对象
#define WKUserDefaultGetObjectForKey(__KEY__)  [WKUserDefaults objectForKey:__KEY__]
//删除对象
#define WKUserDefaultRemoveObjectForKey(__KEY__) \
{\
[WKUserDefaults removeObjectForKey:__KEY__];\
[WKUserDefaults synchronize];\
}


#pragma mark ------------------11.沙盒相关---------------------
//获取temp
#define WKPathTemp NSTemporaryDirectory()
//获取沙盒 Document
#define WKPathDocument [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]
//获取沙盒 Cache
#define WKPathCache [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]

#pragma mark ------------------12.字符串相关---------------------
//字符串高度
#define WKStringHeight(string,widthLimit,font) ([string boundingRectWithSize:CGSizeMake(widthLimit, MAXFLOAT) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil].size.height)

//字符串宽度
#define WKStringWidth(string,font) \
({\
UILabel * label = [[UILabel alloc] initWithFrame:CGRectZero];\
label.font = font;\
label.text = string;\
[label sizeToFit];\
label.bounds.size.width;\
})

#pragma mark ------------------13.View 相关---------------------

//设置圆角边框
#define WKViewBorderRadius(View, Radius, Width, Color)\
\
[View.layer setCornerRadius:(Radius)];\
[View.layer setMasksToBounds:YES];\
[View.layer setBorderWidth:(Width)];\
[View.layer setBorderColor:[Color CGColor]]

//获取View 的宽、高、X、Y
#define WKGetView_Width(Width)  view.frame.size.width
#define WKGetView_Height(Height) view.frame.size.height
#define WKGetView_X(X)      view.frame.origin.x
#define WKGetView_Y(Y)      view.frame.origin.y

#pragma mark ------------------14.常用颜色-dlcat项目---------------------

#define WKColor_White [UIColor whiteColor]
#define WKColor_BG WKHEXColor(@"#f7f7f7");
#define WKColor_Title WKHEXColor(@"#333333");
#define WKColor_Detail_1 WKHEXColor(@"#666666");
#define WKColor_Detail_2 WKHEXColor(@"#999999");
#define WKColor_Purple WKHEXColor(@"#5a489c");
#define WKColor_Red WKHEXColor(@"#ff624f");


其中 十六位色需要给UIColor添加一个扩展,直接复制进去.h 和.m代码就行了
UIColor+HEX.h

//
//  UIColor+HEX.h
//  dlcat
//
//  Created by 王克 on 2015/7/11.
//  Copyright © 2015年 王克. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface UIColor (HEX)

+ (UIColor *)colorWithHexString:(NSString *)color;

//从十六进制字符串获取颜色,
//color:支持@“#123456”、 @“0X123456”、 @“123456”三种格式
+ (UIColor *)colorWithHexString:(NSString *)color alpha:(CGFloat)alpha;

@end

UIColor+HEX.m

//
//  UIColor+HEX.m
//  dlcat
//
//  Created by 王克 on 2015/7/11.
//  Copyright © 2015年 王克. All rights reserved.
//

#import "UIColor+HEX.h"

@implementation UIColor (HEX)
+ (UIColor *)colorWithHexString:(NSString *)color alpha:(CGFloat)alpha{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 characters
    if ([cString length] < 6){
        return [UIColor clearColor];
    }

    if ([cString hasPrefix:@"0X"]) {
        cString = [cString substringFromIndex:2];
    }

    if ([cString hasPrefix:@"#"]) {
        cString = [cString substringFromIndex:1];
    }
    if ([cString length] != 6)  {
        return [UIColor clearColor];
    }
    
    NSRange range;
    range.location = 0;
    range.length = 2;
    //r
    NSString *rString = [cString substringWithRange:range];
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    return [UIColor colorWithRed:((float)r / 255.0f) green:((float)g / 255.0f) blue:((float)b / 255.0f) alpha:alpha];
}

+ (UIColor *)colorWithHexString:(NSString *)color{
    return [self colorWithHexString:color alpha:1.0f];
}
@end

网络接口API部分


/*
 * 注意 改接口基地址的时候一定要改下面H5接口地址
 */

#define baseProduct   @"http://api.XXXX.com"  //正式版公共 根路径
#define baseTestMServer  @"http://test.m.XXX.com"   // 测试服务器 根路径
#define baseTestServer   @"http://test.api.XXXX.com"  //测试服务器2 根路径
#define baseTestXuanZi   @"http://192.168.0.000:8080/xxxx" // 本地调试 根路径 

#define basePath_phone    @"phone"                   //正式版手机项目 路径
#define basePath_wechat     @"wechat"                   //正式版手机微信项目路径

#define kBaseUrlString [NSString stringWithFormat:@"%@/%@", baseTestMServer, basePath_phone]

/*****************H5接口路径***************************************/
#define KBseeH5UrlString @"http://wechat.XXXX.com/mobile"  // 测试服务器微信基地址

//#define KBseeH5UrlString  @"http://xxx.XXXX.com/mobile" // 新版正式微信基地址


//网络请求返回状态
#define HTTP_RETURN_CODE @"code"
#define HTTP_RETURN_DATA @"data"
#define HTTP_RETURN_DESCRIPTION @"description"
#define HTTP_RETURN_RESULT @"result"
#define HTTP_RETURN_SUCCESS @"success"
#define HTTP_RETURN_ERROR @"error"

//秘钥
#define WKAESKeyPostToServer @"xxxxxxxxxxxxxxx"
#define WKSignKeyPostToServer @"xxxxxxxxxxxxxxx"

#define WKAESKeyReceiveFromServer @"xxxxxxxxxxxx"
#define kSignKeyReceiveFromServer @"xxxxxxxxxxxxxxxxxx"

//AppStore APPID
#define AppStoreAppId @"XXXXXXXXXX"

//七鱼 key
#define QYAppKey @"xxxxxxxxxxxxxxx"
//友盟
#define YMShareKey @"xxxxxxxxxxxxxxx"
// 微信
#define WXAppKey @"xxxxxxxxxxxxxxx"
#define WXAppSecret @"xxxxxxxxxxxxxxx"
//QQ
#define QQAppKey @"1vxxxxxxxxxxxxxxx"
//新浪
#define SinaAppKey @"xxxxxxxxxxxxxxx"
#define SinaSecret @"xxxxxxxxxxxxxxx"

/************************存储全局宏定义*********************************/

/********************注册登录接口******************************/
//登录
#define Login_URL [NSString stringWithFormat:@"%@/%@", kBaseUrlString, @"public/login"]
//注册
#define Register_URL [NSString stringWithFormat:@"%@/%@", kBaseUrlString, @"public/reg"]
//退出登录
#define Logout_URL [NSString stringWithFormat:@"%@/%@", kBaseUrlString, @"public/loginOut"]
//发送验证码
#define SendSms_URL [NSString stringWithFormat:@"%@/%@", kBaseUrlString, @"public/sendSms"]
//语音验证码
#define SendVoice_URL [NSString stringWithFormat:@"%@/%@", kBaseUrlString, @"public/sendVoice"]

/*****************************通用接口地址***************************/



/*************************HTML5接口地址*********************************/

#define NoticeDetail_H5 [NSString stringWithFormat:@"%@/%@", KBseeH5UrlString, @"notice/notice_details.html"]



以上就是 本人常用的宏定义,这几年不断总结,删删减减。看看别人的,自己就也添加一个,感觉没用,就再删掉,最后沉淀下来一部分,感觉够项目上用的了。。。。


更新下log 打印,添加了输出文件的地方,每个打印一行,看着好看一点吧。。。

#ifdef DEBUG
//#define WKLog(format, ...) printf("\n[%s] %s [第%d行] %s\n", __TIME__, __FUNCTION__, __LINE__, [[NSString stringWithFormat:format, ## __VA_ARGS__] UTF8String]);

#define WKLog(format, ...) NSLog((@"\n[File: %s]\n" "[Function: %s]\n" "[Line: %d]\n ༺༒_༒༻ \n" format), __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__)

#else
#define WKLog(format, ...)
#endif

更新一下

// 判断是否是iPhone X
#define iPhoneX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO)
// 状态栏高度
#define STATUS_BAR_HEIGHT (iPhoneX ? 44.f : 20.f)
// 导航栏高度
#define NAVIGATION_BAR_HEIGHT (iPhoneX ? 88.f : 64.f)
// tabBar高度
#define TAB_BAR_HEIGHT (iPhoneX ? (49.f+34.f) : 49.f)
// home indicator
#define HOME_INDICATOR_HEIGHT (iPhoneX ? 34.f : 0.f)
iOS学习经验