废话不多说直接上代码,觉得肯定有你们需要的
// iPhoneX 系列相关 (add by 2017年09月22日10:53:06)
// update by 2019年03月27日12:14:03
// 判断是否是ipad
#define isPad ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
// 判断iPhone4系列
#define kiPhone4 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) && !isPad : NO)
// 判断iPhone5系列
#define kiPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) && !isPad : NO)
// 判断iPhone6系列
#define kiPhone6 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(750, 1334), [[UIScreen mainScreen] currentMode].size) && !isPad : NO)
// 判断iphone6+系列
#define kiPhone6Plus ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size) && !isPad : NO)
// 判断iPhoneX
#define IS_IPHONE_X ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) && !isPad : NO)
// 判断iPHoneXr
#define IS_IPHONE_Xr ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(828, 1792), [[UIScreen mainScreen] currentMode].size) && !isPad : NO)
// 判断iPhoneXs
#define IS_IPHONE_Xs ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) && !isPad : NO)
// 判断iPhoneXs Max
#define IS_IPHONE_Xs_Max ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2688), [[UIScreen mainScreen] currentMode].size) && !isPad : NO)
// 在 iPhoneX 系列上 status bar的增量
#define STATUSBAR_HEIGHT_DELTA_ON_IPHONEX ((IS_IPHONE_X || IS_IPHONE_Xr || IS_IPHONE_Xs || IS_IPHONE_Xs_Max) == NO ? 0.0 : 24.0 )
// 在 iPhoneX 系列上 bottom bar的增量
#define BOTTOM_HEIGHT_DELTA_ON_IPHONEX ((IS_IPHONE_X || IS_IPHONE_Xr || IS_IPHONE_Xs || IS_IPHONE_Xs_Max) == NO ? 0.0 : 34.0 )
// 系统控件默认高度随之调整
#define STATUS_BAR_HEIGHT (20.0 + STATUSBAR_HEIGHT_DELTA_ON_IPHONEX)
#define TOP_BAR_HEIGHT (44.0)
#define NAVIGATION_BAR_HEIGHT (STATUS_BAR_HEIGHT + TOP_BAR_HEIGHT)
#define TAB_BAR_HEIGHT (49.0 + BOTTOM_HEIGHT_DELTA_ON_IPHONEX)
#define CELL_DEFAULT_HEIGHT (44.0)
#define EnglishKeyboardHeight (216.0)
#define ChineseKeyboardHeight (252.0)
// (add by 2019年03月25日18:37:56)
// 带自动提示的keypath宏(源自Reactive Cocoa)
#define keypath2(OBJ, PATH) \
(((void)(NO && ((void)OBJ.PATH, NO)), # PATH))
使用,如下图:
此处@keypath(TARGET, KEYPATH)一定要添加@符号,就是为了能预编译出TARGET中所有的KEYPATH属性。
何为预编译?
在main函数执行之前,执行预编译处理。把整个类加载进内存中,在编程过程中,会去匹配TARGET类的类型,当匹配到对应类之后,会去编译查找对应的属性表property list、成员表IRG list、方法表method list。所以这里执行了预编译处理后,就可以提示出TARGET所有的示例变量、属性以及方法。
/**
方法替换 (add by 2017年09月08日17:08:15)
@param c class
@param orig 原函数
@param new 新函数
@return
*/
#define Swizzle(c, orig, new) {\
Method origMethod = class_getInstanceMethod(c, orig);\
Method newMethod = class_getInstanceMethod(c, new);\
if (class_addMethod(c,\
orig,\
method_getImplementation(newMethod),\
method_getTypeEncoding(newMethod)))\
{\
class_replaceMethod(c,\
new,\
method_getImplementation(origMethod),\
method_getTypeEncoding(origMethod));\
} else {\
method_exchangeImplementations(origMethod, newMethod);\
}\
}
// MainScreen Height&Width
#define SCREEN_HEIGHT [[UIScreen mainScreen] bounds].size.height
#define SCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width
// View 坐标(x,y)和宽高(width,height)
#define X(v) (v).frame.origin.x
#define Y(v) (v).frame.origin.y
#define WIDTH(v) (v).frame.size.width
#define HEIGHT(v) (v).frame.size.height
#define MinX(v) CGRectGetMinX((v).frame)
#define MinY(v) CGRectGetMinY((v).frame)
#define MidX(v) CGRectGetMidX((v).frame)
#define MidY(v) CGRectGetMidY((v).frame)
#define MaxX(v) CGRectGetMaxX((v).frame)
#define MaxY(v) CGRectGetMaxY((v).frame)
// 沙盒路径
#define PATH_OF_APP_HOME NSHomeDirectory()
#define PATH_OF_TEMP NSTemporaryDirectory()
#define PATH_OF_DOCUMENT [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
// 加载图片
#define PNGIMAGE(NAME) [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:(NAME) ofType:@"png"]]
#define JPGIMAGE(NAME) [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:(NAME) ofType:@"jpg"]]
#define IMAGE(NAME, EXT) [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:(NAME) ofType:(EXT)]]
// 颜色(RGB)
#define RGBCOLOR(r, g, b) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1]
#define RGBACOLOR(r, g, b, a) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:(a)]
// 随机颜色
#define RANDOM_UICOLOR [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1]
// View 圆角和加边框
#define ViewBorderRadius(View, Radius, Width, Color)\
\
[View.layer setCornerRadius:(Radius)];\
[View.layer setMasksToBounds:YES];\
[View.layer setBorderWidth:(Width)];\
[View.layer setBorderColor:[Color CGColor]]
// View 圆角
#define ViewRadius(View, Radius)\
\
[View.layer setCornerRadius:(Radius)];\
[View.layer setMasksToBounds:YES]
// 当前语言
#define CURRENTLANGUAGE ([[NSLocale preferredLanguages] objectAtIndex:0])
// 本地化字符串
/** NSLocalizedString宏做的其实就是在当前bundle中查找资源文件名“Localizable.strings”(参数:键+注释) */
#define LocalString(x, ...) NSLocalizedString(x, nil)
/** NSLocalizedStringFromTable宏做的其实就是在当前bundle中查找资源文件名“xxx.strings”(参数:键+文件名+注释) */
#define AppLocalString(x, ...) NSLocalizedStringFromTable(x, @"someName", nil)
// 时间间隔
#define kHUDDuration (1.f)
// 一天的秒数
#define SecondsOfDay (24.f * 60.f * 60.f)
// 秒数
#define Seconds(Days) (24.f * 60.f * 60.f * (Days))
// 一天的毫秒数
#define MillisecondsOfDay (24.f * 60.f * 60.f * 1000.f)
// 毫秒数
#define Milliseconds(Days) (24.f * 60.f * 60.f * 1000.f * (Days))
// app 信息
#define APP_STORE_URL @"itms-apps://itunes.apple.com/us/app/xiong-zhao/id1020593660?l=zh&ls=1&mt=8"
#define APP_STORE_INFO_URL @"https://itunes.apple.com/cn/lookup?id=1020593660"
#define VERSION [[[NSBundle mainBundle] infoDictionary] valueForKey:@"CFBundleShortVersionString"]
// block self (deprecated 不推荐使用 仿苹果提示关键字,)
#define BlockWeakObject(o) __typeof(o) __weak
#define BlockWeakSelf BlockWeakObject(self)
// 推荐使用(摘自YYKit)
/**
Synthsize a weak or strong reference.
Example:
@weakify(self)
[self doSomething^{
@strongify(self)
if (!self) return;
...
}];
*/
#ifndef weakify
#if DEBUG
#if __has_feature(objc_arc)
#define weakify(object) autoreleasepool{} __weak __typeof__(object) weak##_##object = object;
#else
#define weakify(object) autoreleasepool{} __block __typeof__(object) block##_##object = object;
#endif
#else
#if __has_feature(objc_arc)
#define weakify(object) try{} @finally{} {} __weak __typeof__(object) weak##_##object = object;
#else
#define weakify(object) try{} @finally{} {} __block __typeof__(object) block##_##object = object;
#endif
#endif
#endif
#ifndef strongify
#if DEBUG
#if __has_feature(objc_arc)
#define strongify(object) autoreleasepool{} __typeof__(object) object = weak##_##object;
#else
#define strongify(object) autoreleasepool{} __typeof__(object) object = block##_##object;
#endif
#else
#if __has_feature(objc_arc)
#define strongify(object) try{} @finally{} __typeof__(object) object = weak##_##object;
#else
#define strongify(object) try{} @finally{} __typeof__(object) object = block##_##object;
#endif
#endif
#endif
// 自定义NSLog,在debug模式下打印,在release模式下取消一切NSLog
#ifdef DEBUG
#define NSLog(FORMAT, ...) fprintf(stderr,"%s:%d\t%s\n",[[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], __LINE__, [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#else
#define NSLog(FORMAT, ...) nil
#endif
//推荐一个插件
XcodeColors
具体配置,github上写的还是蛮清楚的
效果图:
这样在控制台看日志还是比较爽的
// alert
#define Alert(_S_, ...) [[[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:(_S_), ##__VA_ARGS__] delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil] show]
单例宏(宏的高级用法,不会的可以去Google下哈)
下面给个例子:ARC下结合GCD的一个单例的代码
#define SINGLETON_FOR_HEADER(className) \
\
+ (className *)shared##className;
#define SINGLETON_FOR_IMPLEMENTATION(className) \
\
+ (className *)shared##className { \
static className *shared##className = nil; \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
shared##className = [[self alloc] init]; \
}); \
return shared##className; \
}
使用举例:以Student类为例
#import
#import "Global.h"
@interface Student : NSObject
SINGLETON_FOR_HEADER(Student);
@end
#import "Student.h"
@implementation Student
SINGLETON_FOR_IMPLEMENTATION(Student);
@end
// 测试
Student* stu1 = [Student sharedStudent];
Student* stu2 = [Student sharedStudent];
Student* stu3 = [Student sharedStudent];
NSLog(@"%@\n%@\n%@",stu1,stu2,stu3);
打印结果:(地址都是一样的)
这样的话,以后我们写一个单例是不是非常简单呢,不过需要注意的时候我们初始化的时候必须要调sharedClassName这个方法,因为这是一个不完美的单例,但已足够在项目中使用了,前提是我们要约定好。
// 通知相关
#define ADD_OBSERVER(_selector,_name) \
ADD_OBSERVER_WITH_OBJECT(_selector, _name, nil)
//post
#define POST_NOTIFICATION_WITH_OBJECT_AND_INFO(_name, _object, _info) \
([[NSNotificationCenter defaultCenter] postNotificationName:_name object:_object userInfo:(_info)])
#define POST_NOTIFICATION(_name) \
POST_NOTIFICATION_WITH_OBJECT_AND_INFO(_name, nil, nil)
#define POST_NOTIFICATION_WITH_OBJECT(_name, _object) \
POST_NOTIFICATION_WITH_OBJECT_AND_INFO(_name, _object, nil)
#define POST_NOTIFICATION_WITH_INFO(_name, _info) \
POST_NOTIFICATION_WITH_OBJECT_AND_INFO(_name, nil, _info)
//remove
#define REMOVE_OBSERVER(_name) \
([[NSNotificationCenter defaultCenter] removeObserver:self name:_name object:nil])
#define REMOVE_ALL_OBSERVERS(_self) \
([[NSNotificationCenter defaultCenter] removeObserver:_self])
// 检查字符串是否为空(PS:这里认为nil," ", "\n"均是空)
#define strIsEmpty(str) (str==nil || [str length]==0 || [[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0)
// trim string
#define TRIM_STRING(_string) (\
(OBJECT_IS_EMPTY(_string) || NO == [_string isKindOfClass:[NSString class]]) ? \
@"" : [_string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] \
)
// 检查空对象
#define OBJECT_IS_EMPTY(_object) (_object == nil \
|| [_object isKindOfClass:[NSNull class]] \
|| ([_object respondsToSelector:@selector(length)] && [(NSData *)_object length] == 0) \
|| ([_object respondsToSelector:@selector(count)] && [(NSArray *)_object count] == 0))
#define OBJECT_ISNOT_EMPTY(_object) (NO == OBJECT_IS_EMPTY(_object))
#define RETURN_WHEN_OBJECT_IS_EMPTY(_object) if (OBJECT_IS_EMPTY(_object)) { return ; }
#define RETURN_NIL_WHEN_OBJECT_IS_EMPTY(_object) if (OBJECT_IS_EMPTY(_object)) { return nil; }
#define RETURN_EMPTY_WHEN_OBJECT_IS_EMPTY(_object) if (OBJECT_IS_EMPTY(_object)) { return @""; }
#define RETURN_YES_WHEN_OBJECT_IS_EMPTY(_object) if (OBJECT_IS_EMPTY(_object)) { return YES; }
#define RETURN_NO_WHEN_OBJECT_IS_EMPTY(_object) if (OBJECT_IS_EMPTY(_object)) { return NO; }
#define RETURN_ZERO_WHEN_OBJECT_IS_EMPTY(_object) if (OBJECT_IS_EMPTY(_object)) { return 0; }
/** 快速查询一段代码的执行时间 */
/** 用法
TICK
do your work here
TOCK
*/
#define TICK NSDate *startTime = [NSDate date];
#define TOCK NSLog(@"Time:%f", -[startTime timeIntervalSinceNow]);
//由角度转换弧度 由弧度转换角度
#define DegreesToRadian(x) (M_PI * (x) / 180.0)
#define RadianToDegrees(radian) (radian*180.0)/(M_PI)
/*
* 根据当前view 找所在tableview 里的 indexpath
*/
#define INDEXPATH_SUBVIEW_TABLEVIEW(subview,tableview)\
({\
CGRect subviewFrame = [subview convertRect:subview.bounds toView:tableview];\
NSIndexPath *tabIndexPath = [tableview indexPathForRowAtPoint:subviewFrame.origin];\
tabIndexPath;\
})\
/*
* 根据当前view 找所在collectionview 里的 indexpath
*/
#define INDEXPATH_SUBVIEW_COLLECTION(subview,collectionview)\
({\
CGRect subviewFrame = [subview convertRect:subview.bounds toView:collectionview];\
NSIndexPath *tabIndexPath = [collectionview indexPathForItemAtPoint:subviewFrame.origin];\
tabIndexPath;\
})\
/*
* 根据当前view 找所在tableview 里的 tableviewcell
*/
#define CELL_SUBVIEW_TABLEVIEW(subview,tableview)\
({\
CGRect subviewFrame = [subview convertRect:subview.bounds toView:tableview];\
NSIndexPath *indexPath = [tableview indexPathForRowAtPoint:subviewFrame.origin];\
UITableViewCell *tabCell = [tableview cellForRowAtIndexPath:indexPath];\
tabCell;\
})\
希望会给大家带来帮助O(∩_∩)O