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

自己总结的类目Category

程序员文章站 2022-07-15 16:41:59
...

-------------------------给UILabel设置字体,font----------------------------------

#import <UIKit/UIKit.h>

 

#pragma mark ======自带的根据url获取image的方法=======

@interface UIImageView (DispatchLoad)

- (void) setImageFromUrl:(NSString*)urlString;

- (void) setImageFromUrl:(NSString*)urlString

              completion:(void (^)(void))completion;

 

@end

 

@implementation UIImageView (DispatchLoad)

 

- (void) setImageFromUrl:(NSString*)urlString {

    [selfsetImageFromUrl:urlString completion:NULL];

}

 

- (void) setImageFromUrl:(NSString*)urlString

              completion:(void (^)(void))completion {

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        NSURL *url = [NSURL URLWithString:urlString];

        NSData *responseData = [NSData dataWithContentsOfURL:url];

        UIImage *image = [UIImage imageWithData:responseData];

        if (image) {

            dispatch_async(dispatch_get_main_queue(), ^{

                self.image = image;

            });

            dispatch_async(dispatch_get_main_queue(), completion);

        }

    });

}

 

@end

 

 

 

 

@interface UILabel (WebFont)

 

- (void)setFontWithName:(NSString *)fontName defaultName:(NSString *)defaultName size:(float)size;

 

 

@end

 

#import "UILabel+WebFont.h"

#import <CoreText/CoreText.h>

 

static const double kAnimateDuration = .8;

 

@implementation UILabel (WebFont)

 

- (void)setFontWithName:(NSString *)fontName defaultName:(NSString *)defaultName size:(float)size

{

    if ([self isFontDownloaded:fontName]) {

        [self setFont:[UIFont fontWithName:fontName size:size]];

        return;

    } else {

        //download

        [self asynchronouslySetFontName:fontName defaultName:(NSString *)defaultName size:size];

    }

}

 

- (BOOL)isFontDownloaded:(NSString *)fontName

{

    UIFont* aFont = [UIFont fontWithName:fontName size:12.];

    // If the font is already downloaded

    if (aFont && ([aFont.fontName compare:fontName] == NSOrderedSame || [aFont.familyName compare:fontName] == NSOrderedSame)) {

        // Go ahead and display the sample text.

        

        SJBLog(@"Font: 已经下载好,直接设置了字体");

        

        return YES;

    }

    returnNO;

}

 

- (void)asynchronouslySetFontName:(NSString *)fontName  defaultName:(NSString *)defaultName size:(float)size

{

    UIFont* aFont = [UIFont fontWithName:fontName size:12.];

    // If the font is already downloaded

    if (aFont && ([aFont.fontName compare:fontName] == NSOrderedSame || [aFont.familyName compare:fontName] == NSOrderedSame)) {

        // Go ahead and display the sample text.

        [self setFont:[UIFont fontWithName:fontName size:size]];

        

        SJBLog(@"Font: 已经下载好,直接设置了字体");

        return;

    }

    

    CGRect fontFrame = self.frame;

    

    //因为Begin Downloading回调太慢,所以在此判断,如果字体没有下载完成,那么就显示默认字体

    if (![[NSUserDefaultsstandardUserDefaults] objectForKey:[NSStringstringWithFormat:@"kFont_%@",fontName]]) {

        

        [self setFont:[UIFont fontWithName:defaultName size:size]];

        

    }else {

        self.alpha = 0.0;

        self.hidden = YES;

    }

    

    // Create a dictionary with the font's PostScript name.

    NSMutableDictionary *attrs = [NSMutableDictionarydictionaryWithObjectsAndKeys:fontName, kCTFontNameAttribute, nil];

    

    // Create a new font descriptor reference from the attributes dictionary.

    CTFontDescriptorRef desc = CTFontDescriptorCreateWithAttributes((__bridgeCFDictionaryRef)attrs);

    

    NSMutableArray *descs = [NSMutableArrayarrayWithCapacity:0];

    [descs addObject:(__bridge id)desc];

    CFRelease(desc);

    

    __block BOOL errorDuringDownload = NO;

    

    // Start processing the font descriptor..

    // This function returns immediately, but can potentially take long time to process.

    // The progress is notified via the callback block of CTFontDescriptorProgressHandler type.

    // See CTFontDescriptor.h for the list of progress states and keys for progressParameter dictionary.

    CTFontDescriptorMatchFontDescriptorsWithProgressHandler( (__bridgeCFArrayRef)descs, NULL,  ^(CTFontDescriptorMatchingState state, CFDictionaryRef progressParameter) {

        

        if (state == kCTFontDescriptorMatchingDidBegin) {

            dispatch_async( dispatch_get_main_queue(), ^ {

                SJBLog(@"Font: Begin Matching");

                

            });

        } elseif (state == kCTFontDescriptorMatchingDidFinish) {

            dispatch_async( dispatch_get_main_queue(), ^ {

                

                SJBLog(@"Font: Matching Did Finish");

                

                [self setFont:[UIFont fontWithName:fontName size:size]];

                

                // Log the font URL in the console

CTFontRef fontRef = CTFontCreateWithName((__bridge CFStringRef)fontName, 0., NULL);

                CFStringRef fontURL = CTFontCopyAttribute(fontRef, kCTFontURLAttribute);

SJBLog(@"%@", (__bridge NSURL*)(fontURL));

                CFRelease(fontURL);

CFRelease(fontRef);

                

                if (!errorDuringDownload) {

                    SJBLog(@"Font: %@ downloaded", fontName);

                }

                

                self.hidden = NO;

                self.frame = fontFrame;

                [UIViewanimateWithDuration:kAnimateDurationanimations:^{

                    self.alpha = 1.0;

                }completion:^(BOOL finished){

                    

                }];

                

            });

        } elseif (state == kCTFontDescriptorMatchingWillBeginDownloading) {

            dispatch_async( dispatch_get_main_queue(), ^ {

                SJBLog(@"Font: Begin Downloading");

                

            });

        } elseif (state == kCTFontDescriptorMatchingDidFinishDownloading) {

            dispatch_async( dispatch_get_main_queue(), ^ {

                SJBLog(@"Font: Finish downloading");

                

                //下载成功时,存储该字体标示

                NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];

                [userDefault setObject:@"1" forKey:[NSString stringWithFormat:@"kFont_%@",fontName]];

                [userDefault synchronize];

            });

        } elseif (state == kCTFontDescriptorMatchingDownloading) {

            dispatch_async( dispatch_get_main_queue(), ^ {

                // Use the progress bar to indicate the progress of the downloading

                

            });

        } elseif (state == kCTFontDescriptorMatchingDidFailWithError) {

            // An error has occurred.

            // Get the error message

            

            errorDuringDownload = YES;

            

            dispatch_async( dispatch_get_main_queue(), ^ {

                

            });

        }

        

        return (bool)YES;

    });

    

}

 

 

@end

 

 

 

-------------------------TextView的子类,给他加placeholder---------------------------------

 

#import <UIKit/UIKit.h>

 

@interface SJBTextView : UITextView{

    BOOL _shouldDrawPlaceholder;

}

@property (nonatomic) NSString *placeholder;

@property (nonatomic) UIColor *placeholderColor;

 

- (void)_initialize;

- (void)_updateShouldDrawPlaceholder;

- (void)_textChanged:(NSNotification *)notification;

 

@end

 

#import "SJBTextView.h"

 

@implementation SJBTextView

 

- (id)initWithFrame:(CGRect)frame {

    if ((self = [super initWithFrame:frame])) {

        [self _initialize];

    }

    returnself;

}

- (void)setText:(NSString *)string {

    [super setText:string];

    [self_updateShouldDrawPlaceholder];

}

 

 

- (void)setPlaceholder:(NSString *)string {

    if ([string isEqual:_placeholder]) {

        return;

    }

    

    _placeholder = string;

    

    [self_updateShouldDrawPlaceholder];

}

 

#pragma mark - NSObject

 

- (void)dealloc {

    [[NSNotificationCenterdefaultCenter] removeObserver:selfname:UITextViewTextDidChangeNotificationobject:self];

    

}

 

 

#pragma mark - UIView

 

- (id)initWithCoder:(NSCoder *)aDecoder {

    if ((self = [super initWithCoder:aDecoder])) {

        [self _initialize];

    }

    returnself;

}

 

 

- (void)drawRect:(CGRect)rect {

    [super drawRect:rect];

    

    if (_shouldDrawPlaceholder) {

        [_placeholderColorset];

        

        [_placeholderdrawInRect:CGRectMake(8.0f, 5.0f, self.frame.size.width - 16.0f, self.frame.size.height - 16.0f) withAttributes:@{NSForegroundColorAttributeName: self.placeholderColor}];

        

    }

}

 

 

#pragma mark - Private

 

- (void)_initialize {

    [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(_textChanged:) name:UITextViewTextDidChangeNotificationobject:self];

    

    self.placeholderColor = [UIColorcolorWithWhite:0.702falpha:1.0f];

    _shouldDrawPlaceholder = NO;

}

 

 

- (void)_updateShouldDrawPlaceholder {

    BOOL prev = _shouldDrawPlaceholder;

    _shouldDrawPlaceholder = self.placeholder && self.placeholderColor && self.text.length == 0;

    

    if (prev != _shouldDrawPlaceholder) {

        [selfsetNeedsDisplay];

    }

}

 

 

- (void)_textChanged:(NSNotification *)notificaiton {

    [self_updateShouldDrawPlaceholder];

}

 

/*

// Only override drawRect: if you perform custom drawing.

// An empty implementation adversely affects performance during animation.

- (void)drawRect:(CGRect)rect

{

    // Drawing code

}

*/

 

 

@end

 

-------------------------检查新版本----------------------------------

#import <Foundation/Foundation.h>

#import "AFNetworking.h"

@protocol CheckUpdateDelegate <NSObject>

 

@optional

- (void)currentVersionHasNewest;

@end

@interface SJBCheckUpdate : NSObject<UIAlertViewDelegate>

{

    NSString *_updateURL;

}

@property (assign, nonatomic) id <CheckUpdateDelegate>  delegate;

+ (SJBCheckUpdate *)shareInstance;

- (void)checkUpdate;

 

 

@end

 

#import "SJBCheckUpdate.h"

#import "JSON.h"

 

@implementation SJBCheckUpdate

+ (SJBCheckUpdate *)shareInstance

{

    static SJBCheckUpdate *update = nil;

    if (!update)

    {

        update = [[SJBCheckUpdate alloc] init];

    }

    

    return update;

}

 

- (void)checkUpdate

{

    

    NSDictionary *infoDict   = [[NSBundle mainBundle]infoDictionary];

    NSString *currentVersion = infoDict[@"CFBundleShortVersionString"];

    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kUpdateAPPURL, kAPPID];

    NSURL *url = [NSURL URLWithString:urlStr];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperationalloc]initWithRequest:request];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        

        NSDictionary *jsonData   = [operation.responseString JSONValue];

        NSArray      *infoArray  = jsonData[@"results"];

        if (infoArray.count >= 1)

        {

            NSDictionary *releaseInfo   = infoArray[0];

            NSString     *latestVersion = releaseInfo[@"version"];

            NSString     *releaseNotes  = releaseInfo[@"releaseNotes"];

            NSString     *title         = [NSString stringWithFormat:@"%@ %@版本", kAPPName, latestVersion];

            _updateURL = releaseInfo[@"trackViewUrl"];

            

            if ([latestVersion compare:currentVersion] == NSOrderedDescending)

            {

                

                [[NSNotificationCenterdefaultCenter]postNotificationName:@"hasNewVersion"object:nil];

                UIAlertView *alertView = [[UIAlertViewalloc] initWithTitle:title message:releaseNotes delegate:selfcancelButtonTitle:@"忽略"otherButtonTitles:@"App Store下载", nil];

                [alertView show];

            }

            else

            {

                [[NSNotificationCenterdefaultCenter]postNotificationName:@"notNewVersion"object:nil];

                if ([self.delegate respondsToSelector:@selector(currentVersionHasNewest)])

                {

                    [self.delegate currentVersionHasNewest];

                }

            }

        }

        else

        {

            [[NSNotificationCenterdefaultCenter]postNotificationName:@"notNewVersion"object:nil];

            if ([self.delegate respondsToSelector:@selector(currentVersionHasNewest)])

            {

                [self.delegatecurrentVersionHasNewest];

            }

        }

        

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        SJBLog(@"error====%@",error);

        [[NSNotificationCenterdefaultCenter]postNotificationName:@"notNewVersion"object:nil];

        

    }];

    [operation start];

}

 

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

{

    if (buttonIndex == 1)

    {

        [[UIApplicationsharedApplication] openURL:[NSURLURLWithString:_updateURL]];

    }

}

 

@end

 

 

-------------------------NSString的类目,添加判断是否全是数字,是否全是字母,或者以数组开头。---------------------------------

 

#import <Foundation/Foundation.h>

 

@interface NSString (Validation)

 

- (BOOL)isAllDigits;

- (BOOL)isAllAlphaNumericCharacter;

- (BOOL)isStartWithDigit;

 

 

@end

#import "NSString+Validation.h"

 

@implementation NSString (Validation)

 

- (BOOL)isAllDigits

{

    NSCharacterSet *nonNumbers = [[NSCharacterSetdecimalDigitCharacterSet] invertedSet];

    NSRange range = [self rangeOfCharacterFromSet:nonNumbers];

    return range.location == NSNotFound;

}

 

- (BOOL)isAllAlphaNumericCharacter

{

    NSCharacterSet *nonNumbers = [[NSCharacterSetalphanumericCharacterSet] invertedSet];

    NSRange range = [self rangeOfCharacterFromSet:nonNumbers];

    return range.location == NSNotFound;

}

 

- (BOOL)isStartWithDigit

{

    NSCharacterSet *numbers = [NSCharacterSetdecimalDigitCharacterSet];

    NSRange range = [self rangeOfCharacterFromSet:numbers];

    

    return range.location == 0;

}

 

 

@end

 

-------------------------UIViewController的类目,有两个常用的方法,pop,dismiss和一个delegate的获取方法---------------------------------

#import <UIKit/UIKit.h>

#import "SJBAppDelegate.h"

 

@interface UIViewController (Action)

 

- (SJBAppDelegate *)appDelegate;

 

- (void)popViewController;

 

- (void)closeMe;

 

 

@end

 

#import "UIViewController+Action.h"

 

@implementation UIViewController (Action)

 

- (SJBAppDelegate *)appDelegate

{

    SJBAppDelegate *appDelegate = (SJBAppDelegate *)[UIApplication sharedApplication].delegate;

    

    return appDelegate;

}

 

- (void)popViewController

{

    [self.navigationControllerpopViewControllerAnimated:YES];

}

 

- (void)closeMe

{

    [selfdismissViewControllerAnimated:YEScompletion:nil];

}

 

 

@end

 

-------------------------Font下载字体的方法---------------------------------------

#import <UIKit/UIKit.h>

 

@interface SJBFont : UIFont

 

+ (UIFont *)preferedFont:(NSString *)preferedFontName basicFont:(NSString *)basicFontName size:(CGFloat)fontSize;

+ (void)downloadFont:(NSString *)fontName;

 

 

@end

 

#import "SJBFont.h"

#import <CoreText/CoreText.h>

 

@implementation SJBFont

 

+ (UIFont *)preferedFont:(NSString *)preferedFontName basicFont:(NSString *)basicFontName size:(CGFloat)fontSize

{

    UIFont *theFont = [UIFont fontWithName:preferedFontName size:fontSize];

    

    if (theFont && ([theFont.fontName compare:preferedFontName] == NSOrderedSame || [theFont.familyName compare:preferedFontName] == NSOrderedSame)) {

        //

    } else {

        theFont = [UIFont fontWithName:basicFontName size:fontSize];

    }

    

    return theFont;

}

 

+ (void)downloadFont:(NSString *)fontName

{

    UIFont *theFont = [UIFont fontWithName:fontName size:10.0f];

    

    if (!theFont || !([theFont.fontName compare:fontName] == NSOrderedSame || [theFont.familyName compare:fontName] == NSOrderedSame)) {

        NSMutableDictionary *attrs = [NSMutableDictionarydictionaryWithObjectsAndKeys:fontName, kCTFontNameAttribute, nil];

        

        CTFontDescriptorRef desc = CTFontDescriptorCreateWithAttributes((__bridgeCFDictionaryRef)attrs);

        

        NSMutableArray *descs = [NSMutableArrayarrayWithCapacity:0];

        [descs addObject:(__bridge id)desc];

        CFRelease(desc);

        

        __block BOOL errorDuringDownload = NO;

        

        CTFontDescriptorMatchFontDescriptorsWithProgressHandler( (__bridgeCFArrayRef)descs, NULL,  ^(CTFontDescriptorMatchingState state, CFDictionaryRef progressParameter) {

            if (state == kCTFontDescriptorMatchingDidBegin) {

                dispatch_async( dispatch_get_main_queue(), ^ {

                    //

                });

            } elseif (state == kCTFontDescriptorMatchingDidFinish) {

                dispatch_async( dispatch_get_main_queue(), ^ {

                    // Log the font URL in the console

                    SJBLog(@"Font download finished");

                });

            } elseif (state == kCTFontDescriptorMatchingWillBeginDownloading) {

                dispatch_async( dispatch_get_main_queue(), ^ {

                    SJBLog(@"Font Begin Downloading");

                });

            } elseif (state == kCTFontDescriptorMatchingDidFinishDownloading) {

                dispatch_async( dispatch_get_main_queue(), ^ {

                    SJBLog(@"Font Finish downloading");

                });

            } elseif (state == kCTFontDescriptorMatchingDownloading) {

                dispatch_async( dispatch_get_main_queue(), ^ {

                    //

                });

            } elseif (state == kCTFontDescriptorMatchingDidFailWithError) {

//                NSError *error = ((__bridge NSDictionary *)progressParameter)[(id)kCTFontDescriptorMatchingError];

                errorDuringDownload = YES;

 

//                dispatch_async( dispatch_get_main_queue(), ^ {

//                    SJBLog(@"Download error: %@", [error description]);

//                });

            }

            

            return (bool)YES;

        });

    }

}

 

 

@end

 

----------------------------UILabel的子类,加了一个UIEdgeInsets属性-------------------------------

#import <UIKit/UIKit.h>

 

@interface SJBLabel : UILabel

 

@property (nonatomic, assign) UIEdgeInsets insets;

 

 

@end

#import "SJBLabel.h"

 

@implementation SJBLabel

 

- (id)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

        self.insets = UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f);

    }

    returnself;

}

 

- (void)drawTextInRect:(CGRect)rect

{

    UIEdgeInsets insets = _insets;

    

    [superdrawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];

}

 

 

@end

 

----------------------------UIView的类目,Category,删除所有子视图的方法-------------------------------

#import <UIKit/UIKit.h>

 

@interface UIView (Category)

 

- (void)removeAllSubViews;

 

 

@end

 

#import "UIView+Category.h"

 

@implementation UIView (Category)

 

- (void)removeAllSubViews

{

    for (UIView *view in self.subviews) {

        [view removeFromSuperview];

    }

}

 

 

@end

 

 

----------------------------NSString 的类目,parseJson的方法。ios7后的库方法,不用第三方的json框架------------------------------

#import <Foundation/Foundation.h>

 

@interface NSString (JSON)

 

- (id)parseJson;

 

 

@end

 

#import "NSString+JSON.h"

 

@implementation NSString (JSON)

 

- (id)parseJson

{

    NSError *error = nil;

    id returnValue = [NSJSONSerializationJSONObjectWithData:[selfdataUsingEncoding:NSUTF8StringEncoding] options:0error:&error];

    if(error) SJBLog(@"JSON Parsing Error: %@", error);

    

    return returnValue;

}

 

 

@end

 

 --------------------------------UIColor+HexString.h十六进制转化uicolor,借助于mac的Sip工具-------------------

#import <UIKit/UIKit.h>

 

@interface UIColor (HexString)

 

+ (UIColor *)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha;

 

 

@end

 

#import "UIColor+HexString.h"

 

@implementation UIColor (HexString)

 

+ (UIColor *)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha

{

    unsignedint c;

    if ([hexString characterAtIndex:0] == '#') {

        [[NSScannerscannerWithString:[hexString substringFromIndex:1]] scanHexInt:&c];

    } else {

        [[NSScanner scannerWithString:hexString] scanHexInt:&c];

    }

    return [UIColor colorWithRed:((c & 0xff0000) >> 16)/255.0f green:((c & 0xff00) >> 8)/255.0f blue:(c & 0xff)/255.0f alpha:alpha];

}

 

 

@end

 

 --------------------------------UIImage的类目颜色转化为图片---------------------------------

#import <UIKit/UIKit.h>

 

@interface UIImage (PureColorBlock)

 

+ (UIImage *)imageWithColor:(UIColor *)color frame:(CGRect)frame;

 

 

@end

 

#import "UIImage+PureColorBlock.h"

 

@implementation UIImage (PureColorBlock)

 

+ (UIImage *)imageWithColor:(UIColor *)color frame:(CGRect)frame {

    CGRect rect = frame;

    UIGraphicsBeginImageContext(rect.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    

    CGContextSetFillColorWithColor(context, [color CGColor]);

    CGContextFillRect(context, rect);

    

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    

    return image;

}

 

 

@end

 

 ------------UIView的类目Category 可以知道控件的上下左右的边界的值,不用再myLabel.frame.orgin.x+myLabel.frame.size.width那么麻烦了直接用myLabel.right 就行了。其他四个也一样。------------------------------------------

 

#import <UIKit/UIKit.h>

 

 

@interface UIView (Utils)

 

/**

 * Shortcut for frame.origin.x.

 *

 * Sets frame.origin.x = left

 */

@property (nonatomic) CGFloat left;

 

/**

 * Shortcut for frame.origin.y

 *

 * Sets frame.origin.y = top

 */

@property (nonatomic) CGFloat top;

 

/**

 * Shortcut for frame.origin.x + frame.size.width

 *

 * Sets frame.origin.x = right - frame.size.width

 */

@property (nonatomic) CGFloat right;

 

/**

 * Shortcut for frame.origin.y + frame.size.height

 *

 * Sets frame.origin.y = bottom - frame.size.height

 */

@property (nonatomic) CGFloat bottom;

 

/**

 * Shortcut for frame.size.width

 *

 * Sets frame.size.width = width

 */

@property (nonatomic) CGFloat width;

 

/**

 * Shortcut for frame.size.height

 *

 * Sets frame.size.height = height

 */

@property (nonatomic) CGFloat height;

 

/**

 * Shortcut for center.x

 *

 * Sets center.x = centerX

 */

@property (nonatomic) CGFloat centerX;

 

/**

 * Shortcut for center.y

 *

 * Sets center.y = centerY

 */

@property (nonatomic) CGFloat centerY;

 

/**

 * Return the x coordinate on the screen.

 */

@property (nonatomic, readonly) CGFloat screenX;

 

/**

 * Return the y coordinate on the screen.

 */

@property (nonatomic, readonly) CGFloat screenY;

 

/**

 * Return the x coordinate on the screen, taking into account scroll views.

 */

@property (nonatomic, readonly) CGFloat screenViewX;

 

/**

 * Return the y coordinate on the screen, taking into account scroll views.

 */

@property (nonatomic, readonly) CGFloat screenViewY;

 

/**

 * Return the view frame on the screen, taking into account scroll views.

 */

@property (nonatomic, readonly) CGRect screenFrame;

 

/**

 * Shortcut for frame.origin

 */

@property (nonatomic) CGPoint origin;

 

/**

 * Shortcut for frame.size

 */

@property (nonatomic) CGSize size;

 

/**

 * Return the width in portrait or the height in landscape.

 */

@property (nonatomic, readonly) CGFloat orientationWidth;

 

/**

 * Return the height in portrait or the width in landscape.

 */

@property (nonatomic, readonly) CGFloat orientationHeight;

 

/**

 * Finds the first descendant view (including this view) that is a member of a particular class.

 */

- (UIView*)descendantOrSelfWithClass:(Class)cls;

 

/**

 * Finds the first ancestor view (including this view) that is a member of a particular class.

 */

- (UIView*)ancestorOrSelfWithClass:(Class)cls;

 

/**

 * Removes all subviews.

 */

- (void)removeAllSubviews;

 

/**

 Attaches the given block for a single tap action to the receiver.

 @param block The block to execute.

 */

- (void)setTapActionWithBlock:(void (^)(void))block;

 

/**

 Attaches the given block for a long press action to the receiver.

 @param block The block to execute.

 */

- (void)setLongPressActionWithBlock:(void (^)(void))block;

 

 

@end

 

#import "UIView+Utils.h"

 

#import <objc/runtime.h>

 

static char kDTActionHandlerTapBlockKey;

static char kDTActionHandlerTapGestureKey;

static char kDTActionHandlerLongPressBlockKey;

static char kDTActionHandlerLongPressGestureKey;

 

@implementation UIView (Utils)

 

 

- (CGFloat)left {

    returnself.frame.origin.x;

}

 

 

 

- (void)setLeft:(CGFloat)x {

    CGRect frame = self.frame;

    frame.origin.x = x;

    self.frame = frame;

}

 

 

 

- (CGFloat)top {

    returnself.frame.origin.y;

}

 

 

 

- (void)setTop:(CGFloat)y {

    CGRect frame = self.frame;

    frame.origin.y = y;

    self.frame = frame;

}

 

 

 

- (CGFloat)right {

    returnself.frame.origin.x + self.frame.size.width;

}

 

 

 

- (void)setRight:(CGFloat)right {

    CGRect frame = self.frame;

    frame.origin.x = right - frame.size.width;

    self.frame = frame;

}

 

 

 

- (CGFloat)bottom {

    returnself.frame.origin.y + self.frame.size.height;

}

 

 

 

- (void)setBottom:(CGFloat)bottom {

    CGRect frame = self.frame;

    frame.origin.y = bottom - frame.size.height;

    self.frame = frame;

}

 

 

 

- (CGFloat)centerX {

    returnself.center.x;

}

 

 

 

- (void)setCenterX:(CGFloat)centerX {

    self.center = CGPointMake(centerX, self.center.y);

}

 

 

 

- (CGFloat)centerY {

    returnself.center.y;

}

 

 

 

- (void)setCenterY:(CGFloat)centerY {

    self.center = CGPointMake(self.center.x, centerY);

}

 

 

 

- (CGFloat)width {

    returnself.frame.size.width;

}

 

 

 

- (void)setWidth:(CGFloat)width {

    CGRect frame = self.frame;

    frame.size.width = width;

    self.frame = frame;

}

 

 

 

- (CGFloat)height {

    returnself.frame.size.height;

}

 

 

 

- (void)setHeight:(CGFloat)height {

    CGRect frame = self.frame;

    frame.size.height = height;

    self.frame = frame;

}

 

 

 

- (CGFloat)screenX {

    CGFloat x = 0.0f;

    for (UIView* view = self; view; view = view.superview) {

        x += view.left;

    }

    return x;

}

 

 

 

- (CGFloat)screenY {

    CGFloat y = 0.0f;

    for (UIView* view = self; view; view = view.superview) {

        y += view.top;

    }

    return y;

}

 

 

 

- (CGFloat)screenViewX {

    CGFloat x = 0.0f;

    for (UIView* view = self; view; view = view.superview) {

        x += view.left;

        

        if ([view isKindOfClass:[UIScrollView class]]) {

            UIScrollView* scrollView = (UIScrollView*)view;

            x -= scrollView.contentOffset.x;

        }

    }

    

    return x;

}

 

 

 

- (CGFloat)screenViewY {

    CGFloat y = 0;

    for (UIView* view = self; view; view = view.superview) {

        y += view.top;

        

        if ([view isKindOfClass:[UIScrollView class]]) {

            UIScrollView* scrollView = (UIScrollView*)view;

            y -= scrollView.contentOffset.y;

        }

    }

    return y;

}

 

 

 

- (CGRect)screenFrame {

    returnCGRectMake(self.screenViewX, self.screenViewY, self.width, self.height);

}

 

 

 

- (CGPoint)origin {

    returnself.frame.origin;

}

 

 

 

- (void)setOrigin:(CGPoint)origin {

    CGRect frame = self.frame;

    frame.origin = origin;

    self.frame = frame;

}

 

 

 

- (CGSize)size {

    returnself.frame.size;

}

 

 

 

- (void)setSize:(CGSize)size {

    CGRect frame = self.frame;

    frame.size = size;

    self.frame = frame;

}

 

 

 

- (CGFloat)orientationWidth {

    returnUIInterfaceOrientationIsLandscape([UIApplicationsharedApplication].statusBarOrientation)

    ? self.height : self.width;

}

 

 

 

- (CGFloat)orientationHeight {

    returnUIInterfaceOrientationIsLandscape([UIApplicationsharedApplication].statusBarOrientation)

    ? self.width : self.height;

}

 

 

 

- (UIView*)descendantOrSelfWithClass:(Class)cls {

    if ([self isKindOfClass:cls])

        return self;

    

    for (UIView* child in self.subviews) {

        UIView* it = [child descendantOrSelfWithClass:cls];

        if (it)

            return it;

    }

    

    returnnil;

}

 

 

 

- (UIView*)ancestorOrSelfWithClass:(Class)cls {

    if ([self isKindOfClass:cls]) {

        return self;

        

    } else if (self.superview) {

        return [self.superviewancestorOrSelfWithClass:cls];

        

    } else {

        return nil;

    }

}

 

 

 

- (void)removeAllSubviews {

    while (self.subviews.count) {

        UIView* child = self.subviews.lastObject;

        [child removeFromSuperview];

    }

}

 

 

 

- (CGPoint)offsetFromView:(UIView*)otherView {

    CGFloat x = 0.0f, y = 0.0f;

    for (UIView* view = self; view && view != otherView; view = view.superview) {

        x += view.left;

        y += view.top;

    }

    return CGPointMake(x, y);

}

 

 

- (void)setTapActionWithBlock:(void (^)(void))block

{

UITapGestureRecognizer *gesture = objc_getAssociatedObject(self, &kDTActionHandlerTapGestureKey);

    

if (!gesture)

{

gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(__handleActionForTapGesture:)];

[selfaddGestureRecognizer:gesture];

objc_setAssociatedObject(self, &kDTActionHandlerTapGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);

}

    

objc_setAssociatedObject(self, &kDTActionHandlerTapBlockKey, block, OBJC_ASSOCIATION_COPY);

}

 

- (void)__handleActionForTapGesture:(UITapGestureRecognizer *)gesture

{

if (gesture.state == UIGestureRecognizerStateRecognized)

{

void(^action)(void) = objc_getAssociatedObject(self, &kDTActionHandlerTapBlockKey);

        

if (action)

{

action();

}

}

}

 

- (void)setLongPressActionWithBlock:(void (^)(void))block

{

UILongPressGestureRecognizer *gesture = objc_getAssociatedObject(self, &kDTActionHandlerLongPressGestureKey);

    

if (!gesture)

{

gesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(__handleActionForLongPressGesture:)];

[selfaddGestureRecognizer:gesture];

objc_setAssociatedObject(self, &kDTActionHandlerLongPressGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);

}

    

objc_setAssociatedObject(self, &kDTActionHandlerLongPressBlockKey, block, OBJC_ASSOCIATION_COPY);

}

 

- (void)__handleActionForLongPressGesture:(UITapGestureRecognizer *)gesture

{

if (gesture.state == UIGestureRecognizerStateBegan)

{

void(^action)(void) = objc_getAssociatedObject(self, &kDTActionHandlerLongPressBlockKey);

        

if (action)

{

action();

}

}

}

 

 

@end