欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

常用的宏定义

程序员文章站 2022-03-12 08:20:51
...

 

#pragma mark ===============常用的宏定义================

 

#define kScreenHeight [[UIScreen mainScreen] bounds].size.height

#define kScreenWidth [[UIScreen mainScreen] bounds].size.width

#define kStateBarHeight 20

#define kMainHeight (ScreenHeight - StateBarHeight)

#define kMainWidth ScreenWidth

#define kIsIPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)

#define BACKGROUND_CORLOR  [UIColor colorWithRed:222.0/255 green:222.0/255 blue:222.0/255 alpha:1]

#define kUserDefault [NSUserDefaults standardUserDefaults]

#define kApplication [UIApplication sharedApplication]

#define kDataEnv [DataEnvironment sharedDataEnvironment]

#define kDegreesToRadian(x) (M_PI * (x) / 180.0)

#define kRadianToDegrees(radian) (radian*180.0)/(M_PI)

#define kRgbColor(r,g,b) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1]

#define kRgbColor2(r,g,b,a) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:(a)]

/* 根据名称加载有缓存图片 */

#define kImageNamed(name) [UIImage imageNamed:name]

 

//判断系统的当然版本。

#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)

 

#pragma mark ===============不常用的宏定义================

 

#define kSystemError @"系统繁忙,请稍后再试!"

/* 获取系统目录 */

#define kGetDirectory(NSSearchPathDirectory) [NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory, NSUserDomainMask, YES)lastObject]

/* 获取NSFILEMANAGER对象 */

#define kFileManager [NSFileManager defaultManager]

/* 获取程序代理 */

#define kAppdelegate        ((AppDelegate *)[[UIApplication sharedApplication] delegate])

/* 获取任意WINDOW对象 */

#define kWindow             [[[UIApplication sharedApplication] windows] lastObject]

/* 获取KEYWINDOW对象 */

#define kKeyWindow          [[UIApplication sharedApplication] keyWindow]

/* 获取USERDEFAULTS对象 */

#define kNotificactionCenter [NSNotificationCenter defaultCenter]

/* 获取当前控制器的navigationBar */

#define kNavigationBar      [[self navigationController] navigationBar]

/* 简单提示框 */

#define kAlert(title, msg)  [[[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil]show]

/*------------------------------------加载图片---------------------------------------*/

 

/* 根据名称加载无缓存图片 */

#define kNoCacheImagewithName(name, ext) [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:name ofType:ext]]

/* 根据路径加载无缓存图片 */

#define kNoCacheImagewithPath(path) [UIImage imageWithContentsOfFile:path]

 

/*------------------------------------视图------------------------------------------*/

/* 根据TAG获取视图 */

#define kViewWithTag(PARENTVIEW, TAG, CLASS) ((CLASS *)[PARENTVIEW viewWithTag:TAG])

/* 加载NIB文件 */

#define kLOADNIBWITHNAME(CLASS, OWNER) [[[NSBundle mainBundle] loadNibNamed:CLASS owner:OWNER options:nil] lastObject]

/* 异步 */

#define kGCDAsync(block) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block)

/* 同步 */

#define kGCDMain(block) dispatch_async(dispatch_get_main_queue(),block)

/*-----------------------------------界面尺寸--------------------------------------*/

/* 导航栏高度 */

#define kNavigationBarHeight 44

/* 工具栏高度 */

#define kTabBarHeight        49

/* 是否IPad */

#define kIsIpad (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)

/* 是否IPhone */

#define kIsIphone (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)

/* 获取系统信息 */

#define kSystemVersion   [[UIDevice currentDevice] systemVersion]

/* 获取当前语言环境 */

#define kCurrentLanguage [[NSLocale preferredLanguages] objectAtIndex:0]

/* 获取当前APP版本 */

#define kAppVersion      [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]

 

/*-----------------------------------调试相关--------------------------------------*/

#ifdef DEBUG

#define XLOG(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);

#else

#define XLOG(...);

 

#endif

 

//单例。。。。

/*

专门用来保存单例代码

 最后一行不要加

*/

 

// @interface

#define singleton_interface(className) \

+ (className *)shared##className;

 

 

// @implementation

#define singleton_implementation(className) \

static className *_instance; \

+ (id)allocWithZone:(NSZone *)zone \

{ \

    static dispatch_once_t onceToken; \

    dispatch_once(&onceToken, ^{ \

        _instance = [super allocWithZone:zone]; \

    }); \

    return _instance; \

} \

+ (className *)shared##className \

{ \

    static dispatch_once_t onceToken; \

    dispatch_once(&onceToken, ^{ \

        _instance = [[self alloc] init]; \

    }); \

    return _instance; \

 

}

 

 

+ (UIColor*)colorWithInt:(NSInteger)colorValue alpha:(float) a{

    unsigned r = (colorValue&0x00ff0000)>>16;

    unsigned g = (colorValue&0x0000ff00)>>8;

    unsigned b = colorValue&0x000000ff;

    UIColor* color = [UIColorcolorWithRed:r/255.0green:g/255.0blue:b/255.0alpha: a];

    return color;

}

 

+ (UIColor*)colorWithInt:(NSInteger)colorValue{

    unsigned r = (colorValue&0x00ff0000)>>16;

    unsigned g = (colorValue&0x0000ff00)>>8;

    unsigned b = colorValue&0x000000ff;

    UIColor* color = [UIColorcolorWithRed:r/255.0green:g/255.0blue:b/255.0alpha:1.0];

    return color;

}

 

//tag为替换strSrc中所有的sub

+ (NSString*)Repleace:(NSString*)strSrc allsubStr:(NSString*) sub with:(NSString*) tag{

    NSMutableString* resStr = [NSMutableStringstringWithString:strSrc];

    NSRange range = [resStr rangeOfString:sub];

    while (range.length > 0) {

        [resStr replaceCharactersInRange:range withString:tag];

        range = [resStr rangeOfString:sub];

    }

    return resStr;

 

}

 

 

// 电话号和人名加密

+(NSString*) encodeAsByte:(NSString*) val

{

    NSMutableString* sb =  [NSMutableStringstring];

    const char* utf8 = [val UTF8String];

    

    while (*utf8 != '\0') {

        int temp = *utf8;

        NSMutableString* ch = [NSMutableStringstring];

        if (temp < 0) {

            NSString* content = [NSString stringWithFormat:@"%d", -temp];

            [ch appendFormat:@"%d",1];

            [ch appendFormat:@"%ld",(unsigned long)content.length];

            [ch appendString:content];

        }else{

            NSString* content = [NSString stringWithFormat:@"%d", temp];

            [ch appendFormat:@"%d",0];

            [ch appendFormat:@"%ld",(unsigned long)content.length];

            [ch appendString:content];

        }

        [sb appendString:ch];

        utf8++;

    }

    return sb;

 

}

 

+ (BOOL) isTimeOverNow:(NSString*)time

{

    BOOL isOver;

    long long times = [time longLongValue];

    times = (times/1000);

    NSDate* homeTime = [NSDate date];

    long long times2 = [homeTime timeIntervalSince1970];

    times = times - times2;

    if (times <= 0) {

        isOver = YES;

    }else{

        isOver = NO;

    }

    return isOver;

 

}

+ (BOOL)isMobileNumber:(NSString*)mobileNum{

    NSString* MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-35-9])\\d{8}$";

    NSPredicate* regextestmobile = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@",MOBILE];

    if([regextestmobile evaluateWithObject:mobileNum] == YES)

    {

        return YES;

    }else{

        return NO;

    }

 

}

 

 

+ (NSString*)uidStringForDevice

{

    return [[[UIDevicecurrentDevice] identifierForVendor] UUIDString];

}

 

+ (BOOL)isLoginPasswordOK:(NSString *)passWord

{

    int strlength = 0;

    char* p = (char*)[passWord cStringUsingEncoding:NSUnicodeStringEncoding];

    for (int i=0 ; i<[passWord lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {

        if (*p) {

            p++;

            strlength++;

        }

        else {

            p++;

        }

    }

    //    return strlength;

    if (strlength >= 6 && strlength <= 16) {

        return YES;

    }

    returnNO;

}

 

+ (BOOL)isStrA:(NSString*)A containStrB:(NSString*)B

{

    NSRange range = [A rangeOfString:B];

    if (range.location!=NSNotFound) {

        return YES;

    }

    returnNO;

 

}

 

//利用正则表达式验证

+ (BOOL)isValidateEmail:(NSString *)email

{

    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";

    NSPredicate *emailTest = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", emailRegex];

    return [emailTest evaluateWithObject:email];

}

 

//通过区分字符串

 

+ (BOOL)validateEmail:(NSString*)email

{

    if((0 != [email rangeOfString:@"@"].length) &&

       (0 != [email rangeOfString:@"."].length))

    {

        NSCharacterSet* tmpInvalidCharSet = [[NSCharacterSetalphanumericCharacterSet] invertedSet];

        NSMutableCharacterSet* tmpInvalidMutableCharSet = [tmpInvalidCharSet mutableCopy];

        [tmpInvalidMutableCharSet removeCharactersInString:@"_-"];

        

        /*

         *使用compare option 来设定比较规则,如

         *NSCaseInsensitiveSearch是不区分大小写

         *NSLiteralSearch 进行完全比较,区分大小写

         *NSNumericSearch 只比较定符串的个数,而不比较字符串的字面值

         */

        NSRange range1 = [email rangeOfString:@"@"

                                      options:NSCaseInsensitiveSearch];

        

        //取得用户名部分

        NSString* userNameString = [email substringToIndex:range1.location];

        NSArray* userNameArray   = [userNameString componentsSeparatedByString:@"."];

        

        for(NSString* string in userNameArray)

        {

            NSRange rangeOfInavlidChars = [string rangeOfCharacterFromSet: tmpInvalidMutableCharSet];

            if(rangeOfInavlidChars.length != 0 || [string isEqualToString:@""])

                return NO;

        }

        

        //取得域名部分

        NSString *domainString = [email substringFromIndex:range1.location+1];

        NSArray *domainArray   = [domainString componentsSeparatedByString:@"."];

        

        for(NSString *string in domainArray)

        {

            NSRange rangeOfInavlidChars=[string rangeOfCharacterFromSet:tmpInvalidMutableCharSet];

            if(rangeOfInavlidChars.length !=0 || [string isEqualToString:@""])

                return NO;

        }

        

        return YES;

    }

    else {

        return NO;

    }

 

}

 

 

+ (CGSize)sizeOfImageNamed:(NSString*)imageName

{

    return [UIImageimageNamed:imageName].size;

}

 

+ (CGFloat)getIOSVersion

{

    return [[[UIDevicecurrentDevice] systemVersion] floatValue];

}

 

+ (NSString*)iosSysVersion

{

    return [[UIDevicecurrentDevice] systemVersion];

 

}

 

 

//设备名称号

+ (NSString*)getMachine{

    UIDevice* device = [UIDevicecurrentDevice];

    return [device model];

}

 

+ (NSString*)appVersion

{

    NSDictionary *infoDictionary = [[NSBundlemainBundle] infoDictionary];

//    CFShow(CFBridgingRetain(infoDictionary));

    // app版本

    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];

    return app_Version;

}

 

+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size

{

    CGRect rect = CGRectMake(0, 0, size.width, size.height);

    UIGraphicsBeginImageContext(rect.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    

    CGContextSetFillColorWithColor(context, [color CGColor]);

    CGContextFillRect(context, rect);

    

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;

 

}

 

#pragma mark-十六进制转化为字符串

+ (NSString*)stringWithHex:(NSInteger)hexValue

{

    return [NSStringstringWithFormat:@"%lX",(long)hexValue];

}

 

#pragma mark - 字符串转化为十六进制数

+ (NSInteger)hexValueWithStr:(NSString*)hexStr

{

    hexStr = [WOWSUtilsRepleace:hexStr allsubStr:@"#"with:@""];

    NSInteger hexValue = strtoul([hexStr UTF8String],0,16);

    //    Log(@"转换完的数字为:%x",hexValue);

    return hexValue;

 

}

 

#pragma mark - 颜色转换 IOS中十六进制的颜色转换为UIColor

+ (UIColor *) colorWithHexString: (NSString *)colorStr

{

    if (colorStr == nil || ([colorStr isEqual:[NSNull null]]) || colorStr.length == 0) {

        colorStr = @"ffffff";

    }

    NSInteger colorValue = [WOWSUtils hexValueWithStr:colorStr];

    return [WOWSUtilscolorWithInt:colorValue];

 

}

相关标签: