IOS

iOS 常见的宏

2018-11-08  本文已影响0人  leleyinhangjia

如果大家有其他的常用的宏定义,欢迎添加,东西如果不全面,请批评和指正! (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.获取图片和获取版本号

Guideline 2.5.2 - Performance - Software Requirements
tms-services URL Has been deleted from the code

Guideline 5.1.1 - Legal - Privacy - Data Collection and Storage
COVID-19 has been removed

Guideline 5.3.2 - Legal - Gaming, Gambling, and Lotteries
We raise the age limit to 17

本应用面向企业内部用户,用户的登录APP账号信息是管理员在服务端导入或手工添加。

GitHub下载 (新增 iOS 14 真机调试)
GitHub下载 (包括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不可以
NSLog 封装
封装文件

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为基准图
  1. 获取系统版本
#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]])
  1. 字符串是否为空
/**是否为空或是[NSNull null] */
#define IsStrEmpty(_ref)    (((_ref) == nil) || ([(_ref) isEqual:[NSNull null]]) ||([(_ref)isEqualToString:@""]))
  1. 数组是否为空
#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__; \
}

  1. 通过字典的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;

上一篇下一篇

猜你喜欢

热点阅读