iOS 개발 중 간소화된 코드의 매크로 정의

12670 단어

전언


오늘 간소화 프로젝트 코드의 매크로 정의를 꺼내서 공유하겠습니다. 여러분도 간소화 코드에 대한 경험이 있으면 함께 교류할 수 있습니다.
Application
#define APPLICATION   [UIApplication sharedApplication]
#define APPDLE        (AppDelegate*)[APPLICATION delegate]

레이아웃은 순수한 코드와 관련된 프로젝트에서oc문법 자체가 간결하지 않은 특성 때문에 컨트롤 레이아웃은 큰 폭의 코드를 차지하기 때문에 일부 위치, 크기, 중심, 간극 등을 간단명료한 매크로 정의로 쓰면 코드의 가독성을 크게 높일 수 있다(물론 Masonry 프레임워크도 좋은 선택이다).
  • Frame 관련
  • 전참frame 대상, 획득frame의 관련 속성 값
    #define FRAME_ORIGIN(aFrame)              ((aFrame).origin)
    #define FRAME_X(aFrame)                   ((aFrame).origin.x)
    #define FRAME_Y(aFrame)                   ((aFrame).origin.y)
    
    #define FRAME_SIZE(aFrame)                ((aFrame).size)
    #define FRAME_HEIGHT(aFrame)              ((aFrame).size.height)
    #define FRAME_WIDTH(aFrame)               ((aFrame).size.width)
    
    /*  frame   x、y、width、height   */ 
    #define FRAME_CHANGE_X(aFrame,x)          CGRectMake(x, (aFrame).origin.y, (aFrame).size.width, (aFrame).size.height)
    #define FRAME_CHANGE_Y(aFrame,y)          CGRectMake((aFrame).origin.x, y, (aFrame).size.width, (aFrame).size.height)
    #define FRAME_CHANGE_WIDTH(aFrame,w)      CGRectMake((aFrame).origin.x, (aFrame).origin.y, w, (aFrame).size.height)
    #define FRAME_CHANGE_HEIGHT(aFrame,h)     CGRectMake((aFrame).origin.x, (aFrame).origin.y, (aFrame).size.width, h)
    
    //     offset     frame  
    #define FRAME_MOVE_Left(aFrame,offset)    CGRectMake((aFrame).origin.x-(offset), (aFrame).origin.y, (aFrame).size.width, (aFrame).size.height)
    //     offset     frame  
    #define FRAME_MOVE_Right(aFrame,offset)   CGRectMake((aFrame).origin.x+(offset), (aFrame).origin.y, (aFrame).size.width, (aFrame).size.height)
    //     offset     frame  
    #define FRAME_MOVE_Up(aFrame,offset)      CGRectMake((aFrame).origin.x, (aFrame).origin.y-(offset), (aFrame).size.width, (aFrame).size.height)
    //     offset     frame  
    #define FRAME_MOVE_Down(aFrame,offset)    CGRectMake((aFrame).origin.x, (aFrame).origin.y+(offset), (aFrame).size.width, (aFrame).size.height)
    

    전참view 대상, 획득viewframe,bounds 관련 속성 값
    #define VIEW_BOUNDS(aView)       ((aView).bounds)
    
    #define VIEW_FRAME(aView)        ((aView).frame)
    
    #define VIEW_ORIGIN(aView)       ((aView).frame.origin)
    #define VIEW_X(aView)            ((aView).frame.origin.x) 
    #define VIEW_Y(aView)            ((aView).frame.origin.y)
    
    #define VIEW_SIZE(aView)         ((aView).frame.size)
    #define VIEW_HEIGHT(aView)       ((aView).frame.size.height)  //     
    #define VIEW_WIDTH(aView)        ((aView).frame.size.width)   //     
    

    사실 아래 두 개의 매크로는 의미에 따라 VIEW_Right_X(aView),VIEW_Bottom_Y(aView)라고 쓰려고 하였으나 X코드의 자동 알림으로 다음과 같은 형식으로 쓰면 자동 알림 목록에서 VIEW_X(aView),VIEW_Y(aView) 두 개의 매크로와 병렬되어 있어 선택하기 편리하다
    #define VIEW_X_Right(aView)      ((aView).frame.origin.x + (aView).frame.size.width)  //      x  
    #define VIEW_Y_Bottom(aView)     ((aView).frame.origin.y + (aView).frame.size.height) //     y  
    
  • Center 관련
  • #define VIEW_CENTER(aView)       ((aView).center)
    #define VIEW_CENTER_X(aView)     ((aView).center.x)
    #define VIEW_CENTER_Y(aView)     ((aView).center.y)
    
  • 간격에서 어떤 사람들은 이런 매크로를 정의하는 것은 코드를 간소화하는 것이 아니라 오히려 코드를 증가시켰다고 말할 수 있다. 확실히 그렇다.우리는 레이아웃 컨트롤을 할 때 +, - 일부 간격 값과 자주 관련된다. 수백 수천 줄의 코드에서 +, - 의 값을 돌이켜 보면 그 값의 의미를 추측하기 어렵다.만약 이런 매크로로 표시한다면 코드의 가독성을 크게 증가시킬 것이다.
  • #define Space_(space)  (space) //     、     
    

    화면 좌표, 크기 관련
    //        
    #define StateBarHeight          20.f
    //      y  
    #define OffsetStateBarHeight    ((DEVICE_OS_VERSION_VALUE >= 7.0)? StateBarHeight : 0.f)
    
    //          
    #define TopNavBarHeight         40.f
    //        y  
    #define OffsetTopNavBarHeight   (OffsetStateBarHeight + TopNavBarHeight)
    
    //          
    #define BottomTabBarHeight      40.f
    
    
    //     
    #define ScreenHeight            [[UIScreen mainScreen] bounds].size.height
    //     
    #define ScreenWidth             [[UIScreen mainScreen] bounds].size.width
    
    //        
    #define MainHeight              ((DEVICE_OS_VERSION_VALUE >= 7.0)? ScreenHeight : (ScreenHeight - StateBarHeight))
    //        
    #define MainWidth               ScreenWidth
    
    //                
    #define ContentHeight           (MainHeight -OffsetTopNavBarHeight -BottomTabBarHeight)
    

    장치 시스템 관련
  • 장치 현재 아이폰 화면 크기만 표시
  • // x
    #define IS_iPhoneX        ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO)
    // 6P、6sP、7P、8P
    #define IS_iPhone678_Plus ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size) : NO)
    // 6、6s、7、8
    #define IS_iPhone678      ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(750, 1334), [[UIScreen mainScreen] currentMode].size) : NO)
    // 5、5s
    #define IS_iPhone5        ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)
    // 3g、4、4s
    #define IS_iPhone34       ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO)
    
    //    Retina  
    #define IS_Retina      ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? [[UIScreen mainScreen] currentMode].size.width > 320 : NO)
    
  • 시스템 관련
  • // app   
    #define DEVICE_APP_VERSION       (NSString *)[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]
    // app Build   
    #define DEVICE_APP_BUILD         (NSString *)[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]
    
    //      (string)
    #define DEVICE_OS_VERSION        [[UIDevice currentDevice] systemVersion]
    //      (float)
    #define DEVICE_OS_VERSION_VALUE  [DEVICE_OS_VERSION floatValue]
    
    #define IS_IOSVersion_4          (DEVICE_OS_VERSION_VALUE >= 4.0  && DEVICE_OS_VERSION_VALUE < 5.0)
    #define IS_IOSVersion_5          (DEVICE_OS_VERSION_VALUE >= 5.0  && DEVICE_OS_VERSION_VALUE < 6.0)
    #define IS_IOSVersion_6          (DEVICE_OS_VERSION_VALUE >= 6.0  && DEVICE_OS_VERSION_VALUE < 7.0)
    #define IS_IOSVersion_7          (DEVICE_OS_VERSION_VALUE >= 7.0  && DEVICE_OS_VERSION_VALUE < 8.0)
    #define IS_IOSVersion_8          (DEVICE_OS_VERSION_VALUE >= 8.0  && DEVICE_OS_VERSION_VALUE < 9.0)
    #define IS_IOSVersion_9          (DEVICE_OS_VERSION_VALUE >= 9.0  && DEVICE_OS_VERSION_VALUE < 10.0)
    #define IS_IOSVersion_10         (DEVICE_OS_VERSION_VALUE >= 10.0 && DEVICE_OS_VERSION_VALUE < 11.0)
    #define IS_IOSVersion_11         (DEVICE_OS_VERSION_VALUE >= 11.0 && DEVICE_OS_VERSION_VALUE < 12.0)
    

    글꼴 관련
  • 글꼴
  • #define FONT_SIZE(f)            [UIFont systemFontOfSize:(f)]
    #define FONT_BOLD_SIZE(f)       [UIFont boldSystemFontOfSize:(f)]
    #define FONT_ITALIC_SIZE(f)     [UIFont italicSystemFontOfSize:(f)]
    
  • 크기 화면 글꼴 자동 전환 일부 응용 프로그램은 서로 다른 화면에 서로 다른 크기 글꼴을 어울릴 수 있는 좋은 사용자 체험을 원한다면 다음과 같은 매크로 정의를 사용할 수 있다.그러나 응용 프로그램에서 글꼴 크기가 전체적으로 통일되지 않으면 다음과 같은 매크로 정의를 사용하여 글꼴 크기를 적당히 맞추지 마십시오.이것은 네가 개발한 구체적인 상황에 달려 있다. 예를 들어:
  • #define IS_SmallScreen (IS_iPhone5 || IS_iPhone4)
    
    #define MaxFontSize    (IS_SmallScreen ? 21.f : 25.f )
    #define LagerFontSize  (IS_SmallScreen ? 17.f : 19.f )
    #define BigFontSize    (IS_SmallScreen ? 15.f : 17.f )
    #define NormalFontSize (IS_SmallScreen ? 13.f : 15.f )
    #define SmallFontSize  (IS_SmallScreen ? 11.f : 13.f )
    #define MinFontSize    (IS_SmallScreen ? 9.f  : 11.f )
    

    색상 관련
  • 시스템 색상
  • #define COLOR_Clear           [UIColor clearColor]
    #define COLOR_White           [UIColor whiteColor]
    #define COLOR_Black           [UIColor blackColor]
    #define COLOR_Red             [UIColor redColor]
    #define COLOR_DarkGray        [UIColor darkGrayColor]
    #define COLOR_LightGray       [UIColor lightGrayColor]
    #define COLOR_GrayColor       [UIColor grayColor]
    #define COLOR_Green           [UIColor greenColor]
    #define COLOR_BlueColor       [UIColor blueColor]
    #define COLOR_Cyan            [UIColor cyanColor]
    #define COLOR_Yellow          [UIColor yellowColor]
    #define COLOR_Magenta         [UIColor magentaColor]
    #define COLOR_Orange          [UIColor orangeColor]
    #define COLOR_Purple          [UIColor purpleColor]
    #define COLOR_Brown           [UIColor brownColor]
    
  • 색상 변환
  • #define RGBCOLOR(r,g,b)       [UIColor colorWithRed:(r)/255.f green:(g)/255.f blue:(b)/255.f alpha:1.f]
    #define RGBACOLOR(r,g,b,a)    [UIColor colorWithRed:(r)/255.f green:(g)/255.f blue:(b)/255.f alpha:(a)]
    #define HexCOLOR(HexStr)      [UIColor colorWithHexString:HexStr]
    
    + (UIColor *)colorWithHexString:(NSString *)color{
        return [self colorWithHexString:color alpha:1.0f];
    }
    
    
    + (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];
        }
        
        // strip 0X if it appears
        if ([cString hasPrefix:@"0X"])
            cString = [cString substringFromIndex:2];
        if ([cString hasPrefix:@"#"])
            cString = [cString substringFromIndex:1];
        if ([cString length] != 6)
            return [UIColor clearColor];
        
        // Separate into r, g, b substrings
        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];
        
        // Scan values
        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];
    }
    

    문자열 관련
    #define StrOfInterger(interger)  [NSString stringWithFormat:@"%ld",(long)(interger)]
    #define StrOfFloat(float)        [NSString stringWithFormat:@"%f",(float)]
    

    Image 관련
    #define IMG_Name(imgName)        [UIImage imageNamed:(imgName)]
    
    #define IMG_ImgWidth(img)        ((img).size.width)
    #define IMG_ImgHeight(img)       ((img).size.height)
    

    상관관계 확인
    #define STRINGHASVALUE(str)  (str && [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].length > 0)
    #define IsCanUseString(str)     ((str != nil) && ![str isKindOfClass:[NSNull class]] && [str isKindOfClass:[NSString class]] && [str length] > 0 )
    #define IsCanUseArray(arr)      ( arr && (arr != nil) && ![arr isKindOfClass:[NSNull class]] )
    #define IsCanUseDic(dic)        ( dic && (dic != nil) && ![dic isKindOfClass:[NSNull class]] )
    #define IsCanUseObj(obj)        ( obj && (obj != nil) && ![obj isKindOfClass:[NSNull class]] )
    #define IsNullClass(class)      [class isKindOfClass:[NSNull class]]
    

    인쇄 관련
    // mark(NSString    )       
    #define NSLOG_Str(mark,str)       NSLog(@"##%@##--str:%@--",(mark),(str))
    #define NSLOG_Int(mark,int)       NSLog(@"##%@##--int:%ld--",(mark),(int))
    #define NSLOG_Float(mark,float)   NSLog(@"##%@##--float:%f--",(mark),(float))
    #define NSLOG_Bool(mark,bool)     NSLog(@"##%@##--bool:%@--",(mark),(bool) ? @"YES" : @"NO")
    #define NSLOG_Point(mark,point)   NSLog(@"##%@##--x:%f--y:%f--",(mark),(point).x,(point).y)
    #define NSLOG_Size(mark,size)     NSLog(@"##%@##--width:%f--height:%f--",(mark),(size).width,(size).height)
    #define NSLOG_Frame(mark,frame)   NSLog(@"##%@##--x:%f--y:%f--width:%f--height:%f--",(mark),(frame).origin.x,(frame).origin.y,(frame).size.width,(frame).size.height)
    

    저작권 성명: MajorLMJ 기술 블로그의 오리지널 작품으로 전재할 때 반드시 출처와 상응하는 링크를 밝혀야 합니다!

    좋은 웹페이지 즐겨찾기