NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];///silence.SZDemo
/** 允许后台获取用户位置(iOS9.0) */
if([[UIDevice currentDevice].systemVersion floatValue] >= 9.0){}
//获取系统对象
#define kApplication [UIApplication sharedApplication]
#define kAppWindow [UIApplication sharedApplication].delegate.window
#define kAppDelegate [AppDelegate shareAppDelegate]
#define kRootViewController [UIApplication sharedApplication].delegate.window.rootViewController
#define kUserDefaults [NSUserDefaults standardUserDefaults]
#define kNotificationCenter [NSNotificationCenter defaultCenter]
#define kAppDelegate ((AppDelegate *)[UIApplication sharedApplication].delegate)
#define kAppWindow [UIApplication sharedApplication].keyWindow
#define kStatusBarHeight [[UIApplication sharedApplication] statusBarFrame].size.height
#define kNavBarHeight 44.0
#define kTabBarHeight ([[UIApplication sharedApplication] statusBarFrame].size.height>20?83:49)
#define kTopHeight (kStatusBarHeight + kNavBarHeight)
//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 CurrentSystemVersion [[UIDevice currentDevice].systemVersion doubleValue]
//当前语言
#define CurrentLanguage ([NSLocale preferredLanguages] objectAtIndex:0])
//数据验证
#define StrValid(f) (f!=nil && [f isKindOfClass:[NSString class]] && ![f isEqualToString:@""])
#define SafeStr(f) (StrValid(f) ? f:@"")
#define HasString(str,key) ([str rangeOfString:key].location!=NSNotFound)
#define ValidStr(f) StrValid(f)
#define ValidDict(f) (f!=nil && [f isKindOfClass:[NSDictionary class]])
#define ValidArray(f) (f!=nil && [f isKindOfClass:[NSArray class]] && [f count]>0)
#define ValidNum(f) (f!=nil && [f isKindOfClass:[NSNumber class]])
#define ValidClass(f,cls) (f!=nil && [f isKindOfClass:[cls class]])
#define ValidData(f) (f!=nil && [f isKindOfClass:[NSData class]])
//获取一段时间间隔
#define kStartTime CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
#define kEndTime NSLog(@"Time: %f", CFAbsoluteTimeGetCurrent() - start)
//打印当前方法名
#define ITTDPRINTMETHODNAME() ITTDPRINT(@"%s", __PRETTY_FUNCTION__)
//发送通知
#define KPostNotification(name,obj) [[NSNotificationCenter defaultCenter] postNotificationName:name object:obj];
//单例化一个类
#define SINGLETON_FOR_HEADER(className) \
\
+ (className *)shared##className;
#define SINGLETON_FOR_CLASS(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; \
}
//获取当前版本的biuld
#define BIULD_VERSION [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"]
//获取当前版本号
#define BUNDLE_VERSION [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]
//获取当前设备的UDID
#define DIV_UUID [[[UIDevice currentDevice] identifierForVendor] UUIDString]
如果大家有其他的常用的宏定义,欢迎添加,东西如果不全面,请批评和指正! (1. 判断机型
, 2.适配iPhone Xs MAX TabBar和导航,适配6s为基准,ipd,iPhone自适应大小, 3.获取系统版本 iOS 13 , 4.GRB 颜色设置, 5.用于正则式,并非正则式, 6.常用提示框, 7.是否为空或是[NSNull null], 8.字符串是否为空, 9.数组是否为空, 10.便捷方式创建NSNumber类型, 11.便捷创建NSString, 12.线程执行方法, 13.单例创建, 14.通过字典的key 获取NSString,NSNumber,NSDictionary, 15.block 声明 16.NSString转UTF8 17.去空格,首尾空格和换行符,去掉所有的空格),18. 字体设置, 19.获取相关权限,20.弱引用和强引用, 21.获取图片资源, 22.arc 和mrc 会陆续更新最新使用的方法... , 23.字体设置 , 24. 存取值 , 25.获取图片和获取版本号
14:通过字典的key 获取 NSString,NSNumber,NSDictionary ,NSArray (推荐使用)
常用方法: 1.计算Label多行的高度, 2.登录密码正则表达式(大字母或者小写字母,数字,特殊符号,必须有都含有,8-16位) ,3.返回指定的界面 4.获取网络运行商 ,5.自我封装NSdate 常用方法(不完善持续更新...)
附加:Xcode注释和推荐使用
// FIXME: (标示处代码需要修正,使用方法) // FIXME: 😆
// TODO: (标示处有功能代码待编写,使用方法) // TODO:😆
// !!!: (标示处代码需要注意,使用方法) // !!!:😆
// MARK: (标记,和#pragma mark效果相同) // MARK:😆
局部常量:static const NSString *NAME = @“fansion”;//用static修饰后外部不能访问
全局常量:不管在哪个文件夹,外部都能访问;
const NSString *NAME = @“fansion”;//*NAME不能被修改,NAME可以
NSString const *NAME = @“fansion”;//*NAME不能被修改,NAME可以
NSString *const NAME = @“fansion”;//*NAME能被修改,NAME不可以
1.判断机型
//判断是否为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"])
// 判断 iPad
#define DX_UI_IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
// 判断iPhone X
#define DX_Is_iPhoneX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO)
//判断iPHoneXr | 11
#define DX_Is_iPhoneXR ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(828, 1792), [[UIScreen mainScreen] currentMode].size) && !DX_UI_IS_IPAD : NO)
//判断iPHoneXs | 11Pro
#define DX_Is_iPhoneXS ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) && !DX_UI_IS_IPAD : NO)
//判断iPhoneXs Max | 11ProMax
#define DX_Is_iPhoneXS_MAX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2688), [[UIScreen mainScreen] currentMode].size) && !DX_UI_IS_IPAD : NO)
//判断iPhone12_Mini
#define DX_Is_iPhone12_Mini ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1080, 2340), [[UIScreen mainScreen] currentMode].size) && !DX_UI_IS_IPAD : NO)
//判断iPhone12 | 12Pro
#define DX_Is_iPhone12 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1170, 2532), [[UIScreen mainScreen] currentMode].size) && !DX_UI_IS_IPAD : NO)
//判断iPhone12 Pro Max
#define DX_Is_iPhone12_ProMax ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1284, 2778), [[UIScreen mainScreen] currentMode].size) && !DX_UI_IS_IPAD : NO)
//x系列
#define DX_IS_IPhoneX_All (DX_Is_iPhoneX || DX_Is_iPhoneXR || DX_Is_iPhoneXS || DX_Is_iPhoneXS_MAX || DX_Is_iPhone12_Mini || DX_Is_iPhone12 || DX_Is_iPhone12_ProMax)
2.适配 iPhone X TabBar和导航 区别
#define kScreenWidth ([[UIScreen mainScreen] bounds].size.width)
#define kScreenHeight ([[UIScreen mainScreen] bounds].size.height)
/**适配 iPhone X TabBar和导航区别
* Top区别:iPhone X 为例:导航(44 points)+状态栏(44 points)= 88 points
* Iphone 6s为例:导航(44 points)+状态栏(20 points)= 64 points
* Bottom区别:iPhone X 为例: 83 points高度(TabBar) = Danger Area(34 points) + 原来的49 points
* Iphone 6s为例:49 points高度(TabBar) = 49 points
*/
//iPhoneX / iPhoneXS
#define isIphoneX_XS (kScreenWidth ==375.f&& kScreenHeight ==812.f? YES : NO)
//iPhoneXR / iPhoneXSMax
#define isIphoneXR_XSMax (kScreenWidth ==414.f&& kScreenHeight ==896.f? YES : NO)
#define isFullScreen (isIphoneX_XS || isIphoneXR_XSMax)
#define StatusBarHeight (isFullScreen ?44.f:20.f)
#define NavigationBarHeight 44.f
#define TabbarHeight (isFullScreen ? (49.f+34.f) :49.f)
#define TabbarSafeBottomHeight (isFullScreen ?34.f:0.f)
#define StatusBarAndNavigationBarHeight (isFullScreen ?88.f:64.f)
/* iOS设备 */
#define kDevice_Is_iPhone4s ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO)
#define kDevice_Is_iPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)
#define kDevice_Is_iPhone6 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(750, 1334), [[UIScreen mainScreen] currentMode].size) : NO)
#define kDevice_Is_iPhone6Plus ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size) : NO)
#define iPhone6PlusBigMode ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2001), [[UIScreen mainScreen]currentMode].size) : NO)
#define iphoneX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen]currentMode].size) : NO)
#define PW ([UIScreen mainScreen].bounds.size.width/375)
#define PH ([UIScreen mainScreen].bounds.size.height/667)
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
//6s适配参数
#define KsuitParam (kDevice_Is_iPhone6Plus ?1.12:(kDevice_Is_iPhone6?1.0:(iPhone6PlusBigMode ?1.01:(iphoneX ? 1.0 : 0.85)))) //以6s为基准图
获取系统版本
#ifndef __IPHONE_13_0
#define __IPHONE_13_0 130000
#endif
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0
...
#endif
#define IOS_SYSTEM_STRING [[UIDevice currentDevice] systemVersion]
#define IOS11_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 11.0)
#define IOS10_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0)
#define IOS9_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0)
#define IOS8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
#define IOS7_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
4.GRB 颜色设置
/** 颜色RGB */
#define HSVCOLOR(h,s,v) [UIColor colorWithHue:h saturation:s value:v alpha:1]
#define HSVACOLOR(h,s,v,a) [UIColor colorWithHue:h saturation:s value:v alpha:a]
/** 16进制色值参数转换 */
#define UIColorFromRGB(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]
4.ImageNamed 设置
#define ImageNamed(imageName) [UIImage imageNamed:[NSString stringWithFormat:@"%@",imageName]]
5.用于正则式
/** 用于正则式 */
/** 用于正则式 */
#define NUM @"0123456789"
#define ALPHA @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
#define ALPHANUM @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
/** 验证手机号及固话方法 */
#define TelephoneNUM @"^(0[0-9]{2,3})?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$|(^(13[0-9]|15[0|3|6|7|8|9]|18[8|9])\\d{8}$)"
/** 判断社会信用代码证 */
#define SocialCreditNUM @"^([0-9ABCDEFGHJKLMNPQRTUWXY]{2})([0-9]{6})([0-9ABCDEFGHJKLMNPQRTUWXY]{9})([0-9Y])$"
/** 工商税号 */
#define BusinessCirclesNUM @"[0-9]\\\\d{13}([0-9]|X)$"
/** 邮政编码 */
#define CodeNUM @"^[0-8]\\\\d{5}(?!\\\\d)$"
/** 验证身份证号(15位或18位数字) */
#define IDCardNUM @"\\d{14}[[0-9],0-9xX]"
/** 验证Email地址 */
#define EmailNUM @"^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\.\\w+([-.]\\w+)*$"
/** 整数或者小数 */
#define IntAndDecimalNUM @"^[0-9]+([.]{0,1}[0-9]+){0,1}$"
/** 验证URL */
#define URLNUM @"^http://([\\w-]+\.)+[\\w-]+(/[\\w-./?%&=]*)?$"
/** 验证QQ */
#define QQNUM @"[1-9][0-9]\{4,\}"
/** 匹配帐号是否合法 */
#define AccountLegalityNUM @"^[a-zA-Z][a-zA-Z0-9_]{4,15}$"
/** 只能输入汉字 */
#define ChineseCharactersNUM @"^[\u4e00-\u9fa5]{0,}$"
/** 匹配空白行的正则表达式 */
#define SpaceNUM @"^\n\s*\r"
6.常用NSlog打印
/** 打印 NSlog */
#ifdef DEBUG
# define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
/**打印信息*/
#define NSLogI(fmt, ...) NSLog((@"%s 💙INFO [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
/**调试信息*/
#define NSLogD(fmt, ...) NSLog((@"%s 💚DEBUG [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
/**错误信息*/
#define NSLogE(fmt, ...) NSLog((@"%s ❤️ERROR [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
/**未知信息*/
#define NSLogU(fmt, ...) NSLog((@"%s 🧡UNKNOW [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
# define DLog(...)
#endif
6.常用提示框
/** 弹出提示框 UIAlertView */
#define showMessageView(__MESSAGE__) \
UIAlertView *alertView_ = [[UIAlertView alloc] initWithTitle:@"提示" \
message:__MESSAGE__ \
delegate:nil \
cancelButtonTitle:@"确定" \
otherButtonTitles:nil]; \
[alertView_ show];
/** 弹出提示框 UIAlertController */
#define showMessageController(MESSAGE,VC) \
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:MESSAGE preferredStyle:UIAlertControllerStyleAlert]; \
UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]; \
[alertController addAction:action]; \
[VC presentViewController:alertController animated:YES completion:nil]
7.是否为空或是[NSNull null]
/**是否为空或是[NSNull null] */
#define NotNilAndNull(_ref) (((_ref) != nil) && (![(_ref) isEqual:[NSNull null]]))
#define IsNilOrNull(_ref) (((_ref) == nil) || ([(_ref) isEqual:[NSNull null]])
字符串是否为空
/**是否为空或是[NSNull null] */
#define IsStrEmpty(_ref) (((_ref) == nil) || ([(_ref) isEqual:[NSNull null]]) ||([(_ref)isEqualToString:@""]))
数组是否为空
#define IsArrEmpty(_ref) (((_ref) == nil) || ([(_ref) isEqual:[NSNull null]]) ||([(_ref) count] == 0))
10.便捷方式创建NSNumber类型
/** 便捷方式创建NSNumber类型 */
#undef __INT
#define __INT( __x ) [NSNumber numberWithInt:(NSInteger)__x]
#undef __UINT
#define __UINT( __x ) [NSNumber numberWithUnsignedInt:(NSUInteger)__x]
#undef __FLOAT
#define __FLOAT( __x ) [NSNumber numberWithFloat:(float)__x]
#undef __DOUBLE
#define __DOUBLE( __x ) [NSNumber numberWithDouble:(double)__x]
11.便捷创建NSString
/** 便捷创建NSString */
#undef STR_FROM_INT
#define STR_FROM_INT( __x ) [NSString stringWithFormat:@"%d", (__x)]
12.线程执行方法
/** 线程执行方法 */
#define Foreground_Begin dispatch_async(dispatch_get_main_queue(), ^{
#define Foreground_End });
#define Background_Begin dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{\
@autoreleasepool {
#define Background_End }\
});
13.单例创建
/** 线程执行方法 */
#undef AS_SINGLETON
#define AS_SINGLETON( __class ) \
+ (__class *)sharedInstance;
#undef DEF_SINGLETON
#define DEF_SINGLETON( __class ) \
+ (__class *)sharedInstance \
{ \
static dispatch_once_t once; \
static __class * __singleton__; \
dispatch_once( &once, ^{ __singleton__ = [[__class alloc] init]; } ); \
return __singleton__; \
}
通过字典的key 获取NSString,NSNumber,NSDictionary ,NSArray
.h创建
/** 通过字典的key 获取value (判断转换为)NSString */
extern NSString* EncodeStringFromDic(NSDictionary *dic, NSString *key);
/** 通过字典的key 获取value (判断转换为)NSNumber */
extern NSNumber* EncodeNumberFromDic(NSDictionary *dic, NSString *key);
extern NSDictionary *EncodeDicFromDic(NSDictionary *dic, NSString *key);
extern NSArray *EncodeArrayFromDic(NSDictionary *dic, NSString *key);
extern NSArray *EncodeArrayFromDicUsingParseBlock(NSDictionary *dic, NSString *key, id(^parseBlock)(NSDictionary *innerDic));
.m创建
NSString* EncodeStringFromDic(NSDictionary *dic, NSString *key)
{
id temp = [dic objectForKey:key];
if ([temp isKindOfClass:[NSString class]])
{
return temp;
}
else if ([temp isKindOfClass:[NSNumber class]])
{
return [temp stringValue];
}
return nil;
}
NSNumber* EncodeNumberFromDic(NSDictionary *dic, NSString *key)
{
id temp = [dic objectForKey:key];
if ([temp isKindOfClass:[NSString class]])
{
return [NSNumber numberWithDouble:[temp doubleValue]];
}
else if ([temp isKindOfClass:[NSNumber class]])
{
return temp;
}
return nil;
}
NSDictionary *EncodeDicFromDic(NSDictionary *dic, NSString *key)
{
id temp = [dic objectForKey:key];
if ([temp isKindOfClass:[NSDictionary class]])
{
return temp;
}
return nil;
}
NSArray *EncodeArrayFromDic(NSDictionary *dic, NSString *key)
{
id temp = [dic objectForKey:key];
if ([temp isKindOfClass:[NSArray class]])
{
return temp;
}
return nil;
}
NSArray *EncodeArrayFromDicUsingParseBlock(NSDictionary *dic, NSString *key, id(^parseBlock)(NSDictionary *innerDic))
{
NSArray *tempList = EncodeArrayFromDic(dic, key);
if ([tempList count])
{
NSMutableArray *array = [NSMutableArray arrayWithCapacity:[tempList count]];
for (NSDictionary *item in tempList)
{
id dto = parseBlock(item);
if (dto) {
[array addObject:dto];
}
}
return array;
}
return nil;
}
15.block 声明
#ifdef NS_BLOCKS_AVAILABLE
typedef void (^ZLyBasicBlock)(void);
typedef void (^ZLyOperationCallBackBlock)(BOOL isSuccess, NSString *errorMsg);
typedef void (^ZLyArrayBlock)(NSArray *list);
#endif
16.NSString转UTF8
#define OC(str) [NSString stringWithCString:(str) encoding:NSUTF8StringEncoding]
17.去空格,首尾空格和换行符,去掉所有的空格
/** 去掉首尾空格和换行符 */
#define FirstAndLastSpace(str) [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]
/**去掉所有空格*/
#define RemoveAllSpaces(str) [str stringByReplacingOccurrencesOfString:@" " withString:@""]
18.字体设置
#define Font_Size(f) [UIFont systemFontOfSize:(f)]
#define Font_Bold_Size(f) [UIFont boldSystemFontOfSize:(f)]
#define Font_Italic_Size(f) [UIFont italicSystemFontOfSize:(f)]
#define FontMediumSize(s) [UIFont fontWithName:@"xxx" size:s]
#define FontRegularSize(s) [UIFont fontWithName:@"xxx" size:s]
19.获取相关权限. 相加,地位等
//获取相机权限状态
#define CameraStatus [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]
#define CameraDenied ((CameraStatus == AVAuthorizationStatusRestricted)||(CameraStatus == AVAuthorizationStatusDenied))
#define CameraAllowed (!CameraDenyed)
/** 定位权限*/
#define LocationStatus [CLLocationManager authorizationStatus];
#define LocationAllowed ([CLLocationManager locationServicesEnabled] && !((status == kCLAuthorizationStatusDenied) || (status == kCLAuthorizationStatusRestricted)))
#define LocationDenied (!LocationAllowed)
/** 消息推送权限*/
#define PushClose (([[UIDevice currentDevice].systemVersion floatValue]>=8.0f)?(UIUserNotificationTypeNone == [[UIApplication sharedApplication] currentUserNotificationSettings].types):(UIRemoteNotificationTypeNone == [[UIApplication sharedApplication] enabledRemoteNotificationTypes]))
#define PushOpen (!PushClose)
20.弱引用,强引用
#define WeakSelf(type) __weak typeof(type) weak##type = type;
#define StrongSelf(type) __strong typeof(type) type = weak##type;
21.获取图片资源
#define kGetImage(imageName) [UIImage imageNamed:[NSString stringWithFormat:@"%@",imageName]]
22.arc OR mrc
#if __has_feature(objc_arc)
// ARC
#else
// MRC
#endif
23.字体设置
#define IsIphone6P SCREEN_WIDTH==414
#define SizeScale (IsIphone6P ? 1.5 : 1)
#define kFontSize(value) value*SizeScale
#define kFont(value) [UIFont systemFontOfSize:value*SizeScale]
/**36px 导航栏文字**/
#define ZLyFont_36 [UIFont systemFontOfSize:36 / (([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)?750.0:1536.0) * [UIScreen mainScreen].bounds.size.width]
/**32px 按钮文字,标题文字**/
#define ZLyFont_32 [UIFont systemFontOfSize:32 / (([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)?750.0:1536.0) * [UIScreen mainScreen].bounds.size.width]
/**30px 正文内容**/
#define ZLyFont_30 [UIFont systemFontOfSize:30 / (([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)?750.0:1536.0) * [UIScreen mainScreen].bounds.size.width]
/**28px 填写描述**/
#define ZLyFont_28 [UIFont systemFontOfSize:28 / (([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)?750.0:1536.0) * [UIScreen mainScreen].bounds.size.width]
/**26px 辅助文字**/
#define ZLyFont_26 [UIFont systemFontOfSize:26 / (([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)?750.0:1536.0) * [UIScreen mainScreen].bounds.size.width]
/**24px 辅助文字**/
#define ZLyFont_24 [UIFont systemFontOfSize:24 / (([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)?750.0:1536.0) * [UIScreen mainScreen].bounds.size.width]
/**22px 说明性文字**/
#define ZLyFont_22 [UIFont systemFontOfSize:22 / (([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)?750.0:1536.0) * [UIScreen mainScreen].bounds.size.width]
/**20px 辅助说明性文字**/
#define ZLyFont_20 [UIFont systemFontOfSize:20 / (([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)?750.0:1536.0) * [UIScreen mainScreen].bounds.size.width]
/**100px **/
#define ZLyFont_100 [UIFont systemFontOfSize:100 / (([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)?750.0:1536.0) * [UIScreen mainScreen].bounds.size.width]
24 存取数据
//存值
#define kSaveMyDefault(A,B) [[NSUserDefaults standardUserDefaults] setObject:B forKey:A]
//取值
#define kFetchMyDefault(A) [[NSUserDefaults standardUserDefaults] objectForKey:A]
#define kSaveZLyDefault(A,B) [[NSUserDefaults standardUserDefaults] setInteger:B forKey:A]
#define kFetchZLyDefault(A) [[NSUserDefaults standardUserDefaults] integerForKey:A]
25.获取图片和版本号
#define ImageName(name) [UIImage imageNamed:name]
#define FontSize(size) [UIFont systemFontOfSize:size]
#define VERSION (NSString *)[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]
1.计算Label多行的高度
/**
1.根据text的font和字符串自动算出size(重点)
2.本身最大宽度
MAXFLOAT:最大高度为最大浮点数
**/
-(CGFloat)calculateString:(NSString *)str Width:(NSInteger)width Font:(NSInteger)font {
CGSize size = [str boundingRectWithSize:CGSizeMake(width, 100000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:font]} context:nil].size;
return size.height;
}
2.登录密码正则表达式
NSString *regex =@"(?=.*?[a-zA-Z])(?=.*?[0-9])(?=.*?[^\\w\\s]).{8,16}";
NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
// 字符串判断,然后BOOL值
BOOL result1 = [predicate1 evaluateWithObject:newpasswd];
3.返回指定的界面
for (UIViewController *controller in self.navigationController.viewControllers) {
if ([controller isKindOfClass:[要返回的类名 class]]) {
[self.navigationController popToViewController:controller animated:YES];
}
}
或者dissVC
[self.presentingViewController.presentingvc dismissViewControllerAnimated:NO completion:nil];
4.获取网络运营商
//获取网络运营商
+(NSString *)CTTelephonyNetworkProviders
{
//获取本机运营商名称
CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
CTCarrier *carrier = [info subscriberCellularProvider];
//当前手机所属运营商名称
NSString *mobile;
//先判断有没有SIM卡,如果没有则不获取本机运营商
if (!carrier.isoCountryCode) {
// NSLog(@"没有SIM卡");
mobile = @"无运营商";
}else{
mobile = [carrier carrierName];
}
return mobile;
}
5.NSdate 转换(nsstring 格式)
+ (NSInteger)compareDate:(NSString*)startDate withDate:(NSString*)endDate;
/**只算小时和分钟 HH:mm **/
+ (NSString *)dateStringWithHouseAndSecond:(NSString *)dateStr;
/* YYYY-MM-dd EEE HH:mm */
+(NSString *)dateString:(NSString *)dateStr;
/**EEE**/
+(NSString *)dateWeekString:(NSString *)dateStr;
/**MM-dd**/
+(NSString *)dateMonthAndDayString:(NSString *)dateStr;
/** yyyy-MM-dd HH:mm ----- MM-dd **/
+(NSString *)dateNewMonthAndDayString:(NSString *)dateStr;
/** yyyy-MM-dd HH:mm ----- yyyy **/
+(NSString *)dateAndYearString:(NSString *)dateStr;
/** yyyy-MM-dd HH:mm ----- yyyy-MM-dd 新增**/
+(NSString *)dateAndYearAndMonthAndDayString:(NSString *)dateStr;
/**获取当前时间**/
+(NSString*)getCurrentTimes;
/**获取周数 周日-周六 (国外日历)**/
+(NSString *)obtainCurrentDateAndUpdateInterface:(NSString *)datestring;
/****获取当前的时间 YYYY-MM-dd HH:mm****/
+(NSString*)getCurrentTimesYearAndMonthAndDayAndHoursAndSecond;
//获取当前的时间 只展示时间HH
+(NSString*)getCurrentTimesHH;
//获取当前的时间 YYYY-MM-dd HH:mm:ss
+(NSString*)getCurrentTimesYYYYMMddHHmmss ;
//获取当前的时间 YYYY-MM-dd HH:mm --- HH:mm
+(NSString *)dateHoursAndMinuesString:(NSString *)dateStr;
+ (NSString *)getCurrentWeek;
#pragma mark 获取当前第一天日期(周日)
+ (NSString *)obtainCurrentDateSunday:(NSString *)sundayString;
/**获取周数 周日-周六 (国外日历)**/
#pragma mark 获取当前第一天日期(周一)
+ (NSString *)obtainCurrentDateMonday:(NSString *)mondayString ;
/**获取周数 周日-周六 (国外日历)**/
#pragma mark 获取当前第一天日期(周二)
+ (NSString *)obtainCurrentDateTuesday:(NSString *)TuesdayString;
/**获取周数 周日-周六 (国外日历)**/
#pragma mark 获取当前第一天日期(周三)
+ (NSString *)obtainCurrentDateWenday:(NSString *)WendayString;
/**获取周数 周日-周六 (国外日历)**/
#pragma mark 获取当前第一天日期(周四)
+ (NSString *)obtainCurrentDateThursday:(NSString *)ThursdayString;
/**获取周数 周日-周六 (国外日历)**/
#pragma mark 获取当前第一天日期(周五)
+ (NSString *)obtainCurrentDateFriday:(NSString *)FridayString;
#pragma mark 获取当前第后天日期(周六)
+ (NSString *)obtainCurrentDateSaturday:(NSString *)SaturdayString;
字符串反转
第一种:
- (NSString *)reverseWordsInString:(NSString *)str
{
NSMutableString *newString = [[NSMutableString alloc] initWithCapacity:str.length];
for (NSInteger i = str.length - 1; i >= 0 ; i --)
{
unichar ch = [str characterAtIndex:i];
[newString appendFormat:@"%c", ch];
}
return newString;
}
//第二种:
- (NSString*)reverseWordsInString:(NSString*)str
{
NSMutableString *reverString = [NSMutableString stringWithCapacity:str.length];
[str enumerateSubstringsInRange:NSMakeRange(0, str.length) options:NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[reverString appendString:substring];
}];
return reverString;
}
模态推出透明界面
UIViewController *vc = [[UIViewController alloc] init];
UINavigationController *na = [[UINavigationController alloc] initWithRootViewController:vc];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
na.modalPresentationStyle = UIModalPresentationOverCurrentContext;
}
else
{
self.modalPresentationStyle=UIModalPresentationCurrentContext;
}
[self presentViewController:na animated:YES completion:nil];
禁止锁屏,
默认情况下,当设备一段时间没有触控动作时,iOS会锁住屏幕。但有一些应用是不需要锁屏的,比如视频播放器。
[UIApplication sharedApplication].idleTimerDisabled = YES;
或
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
iOS 获取汉字的拼音
+ (NSString *)transform:(NSString *)chinese
{
//将NSString装换成NSMutableString
NSMutableString *pinyin = [chinese mutableCopy];
//将汉字转换为拼音(带音标)
CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
NSLog(@"%@", pinyin);
//去掉拼音的音标
CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
NSLog(@"%@", pinyin);
//返回最近结果
return pinyin;
}
NSArray 快速求总和 最大值 最小值 和 平均值
NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil];
CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];
CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue];
CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];
NSLog(@"%f\n%f\n%f\n%f",sum,avg,max,min);
关于NSDateFormatter的格式
G: 公元时代,例如AD公元
yy: 年的后2位
yyyy: 完整年
MM: 月,显示为1-12
MMM: 月,显示为英文月份简写,如 Jan
MMMM: 月,显示为英文月份全称,如 Janualy
dd: 日,2位数表示,如02
d: 日,1-2位显示,如 2
EEE: 简写星期几,如Sun
EEEE: 全写星期几,如Sunday
aa: 上下午,AM/PM
H: 时,24小时制,0-23
K:时,12小时制,0-11
m: 分,1-2位
mm: 分,2位
s: 秒,1-2位
ss: 秒,2位
S: 毫秒
阿拉伯数字转中文格式
+(NSString *)translation:(NSString *)arebic
{
NSString *str = arebic;
NSArray *arabic_numerals = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0"];
NSArray *chinese_numerals = @[@"一",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"零"];
NSArray *digits = @[@"个",@"十",@"百",@"千",@"万",@"十",@"百",@"千",@"亿",@"十",@"百",@"千",@"兆"];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:chinese_numerals forKeys:arabic_numerals];
NSMutableArray *sums = [NSMutableArray array];
for (int i = 0; i < str.length; i ++) {
NSString *substr = [str substringWithRange:NSMakeRange(i, 1)];
NSString *a = [dictionary objectForKey:substr];
NSString *b = digits[str.length -i-1];
NSString *sum = [a stringByAppendingString:b];
if ([a isEqualToString:chinese_numerals[9]])
{
if([b isEqualToString:digits[4]] || [b isEqualToString:digits[8]])
{
sum = b;
if ([[sums lastObject] isEqualToString:chinese_numerals[9]])
{
[sums removeLastObject];
}
}else
{
sum = chinese_numerals[9];
}
if ([[sums lastObject] isEqualToString:sum])
{
continue;
}
}
[sums addObject:sum];
}
NSString *sumStr = [sums componentsJoinedByString:@""];
NSString *chinese = [sumStr substringToIndex:sumStr.length-1];
NSLog(@"%@",str);
NSLog(@"%@",chinese);
return chinese;
}
字符串中是否含有中文
+ (BOOL)checkIsChinese:(NSString *)string
{
for (int i=0; i<string.length; i++)
{
unichar ch = [string characterAtIndex:i];
if (0x4E00 <= ch && ch <= 0x9FA5)
{
return YES;
}
}
return NO;
}
dispatch_group的使用
dispatch_group_t dispatchGroup = dispatch_group_create();
dispatch_group_enter(dispatchGroup);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"第一个请求完成");
dispatch_group_leave(dispatchGroup);
});
dispatch_group_enter(dispatchGroup);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"第二个请求完成");
dispatch_group_leave(dispatchGroup);
});
dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^(){
NSLog(@"请求完成");
});
UITextField每四位加一个空格,实现代理
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// 四位加一个空格
if ([string isEqualToString:@""])
{
// 删除字符
if ((textField.text.length - 2) % 5 == 0)
{
textField.text = [textField.text substringToIndex:textField.text.length - 1];
}
return YES;
}
else
{
if (textField.text.length % 5 == 0)
{
textField.text = [NSString stringWithFormat:@"%@ ", textField.text];
}
}
return YES;
}
获取手机安装的应用
Class c =NSClassFromString(@"LSApplicationWorkspace");
id s = [(id)c performSelector:NSSelectorFromString(@"defaultWorkspace")];
NSArray *array = [s performSelector:NSSelectorFromString(@"allInstalledApplications")];
for (id item in array)
{
NSLog(@"%@",[item performSelector:NSSelectorFromString(@"applicationIdentifier")]);
//NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleIdentifier")]);
NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleVersion")]);
NSLog(@"%@",[item performSelector:NSSelectorFromString(@"shortVersionString")]);
}
应用内打开系统设置界面
//iOS8之后
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
//如果App没有添加权限,显示的是设定界面。如果App有添加权限(例如通知),显示的是App的设定界面。
如何获取WebView所有的图片地址,
在网页加载完成时,通过js获取图片和添加点击的识别方式
//WKWebView
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
static NSString * const jsGetImages =
@"function getImages(){\
var objs = document.getElementsByTagName(\"img\");\
var imgScr = '';\
for(var i=0;i<objs.length;i++){\
imgScr = imgScr + objs[i].src + '+';\
};\
return imgScr;\
};";
[webView evaluateJavaScript:jsGetImages completionHandler:nil];
[webView evaluateJavaScript:@"getImages()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"%@",result);
}];
}
获取到webview的高度
CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
获取UIColor的RGBA值
UIColor *color = [UIColor colorWithRed:0.2 green:0.3 blue:0.9 alpha:1.0];
const CGFloat *components = CGColorGetComponents(color.CGColor);
NSLog(@"Red: %.1f", components[0]);
NSLog(@"Green: %.1f", components[1]);
NSLog(@"Blue: %.1f", components[2]);
NSLog(@"Alpha: %.1f", components[3]);
UILabel显示Html
NSString *htmlString = @"Some html string";
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];
UILabel *label = [[UILabel alloc] initWithFrame:self.view.bounds];
label.attributedText = attrStr;
[self.view addSubview:label];
网友评论