`
zjjzmw1
  • 浏览: 1366189 次
  • 性别: Icon_minigender_1
  • 来自: 开封
社区版块
存档分类
最新评论

自己总结的类目Category

    博客分类:
  • iOS
阅读更多

-------------------------给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

 

分享到:
评论

相关推荐

    真实类目跳转代码

    ### 总结 “真实类目跳转代码”是Web开发中常见且重要的组成部分,它不仅能够提升用户体验,还对于网站的结构优化和SEO有着不可忽视的作用。通过JavaScript,我们能够灵活地实现各种跳转逻辑,无论是基础的跳转还是...

    ios开发类目及协议

    总结来说,在iOS开发中,类目(Category)和协议(Protocol)是提高代码复用性和解耦的关键工具。类目允许开发者扩展类的功能而不改变原有类的实现,协议则用于定义和实现一套方法标准,实现对象间的委托关系。在...

    陈维政-2022080717014-人工智能1班-第八次MySQL实验报告.docx

    - **表名**:Category - **字段**: - CategoryID (主键):类目ID。 - CategoryName:类目名称。 - ParentCategoryID (外键):如果该类目有父类目,则关联到CategoryID。 #### 5. 订单表 - **表名**:Order - **...

    vue+echarts完整显示x轴的示例以及完整案例.zip

    总结来说,解决ECharts X轴显示不全的问题,可以通过调整文本标签的旋转角度、设置显示间隔、利用数据区域缩放以及自定义标签内容等方法。结合Vue组件化开发,这些解决方案可以方便地集成到实际项目中,提升用户体验...

    api接口查询

    - `cid`:商品类目ID,必须是叶子类目ID,存储在`pigcms_product`表的`category_id`字段。 - `cat_name`:商品类目名称,存储在`pigcms_product_category`表的`cat_name`字段。 - `props`:产品的关键属性列表,格式...

    阿里巴巴电商认识图谱.pdf

    电商认知图谱的核心在于构建一个围绕用户需求的商品管理体系,它不仅仅是一个简单的类目-属性-属性值体系,而是包含了更丰富的语义信息和概念关系。在这个图谱中,商品不再局限于单一的属性描述,而是成为了不同概念...

    【JavaScript源代码】vue echarts实现横向柱状图.docx

    3. `yAxis`:定义纵轴,类型为类目轴 (`type: 'category'`),并进行倒序排列 (`inverse: true`),同时设置标签、刻度线和轴线的颜色和样式。 ECharts 的配置选项非常灵活,可以根据具体需求调整。例如,`colors` ...

    Repeater中嵌套Repeater的示例介绍

    本示例将详细介绍如何在`Repeater`中嵌套使用另一个`Repeater`,以展示一个类目与该类目下的产品的层级关系。 首先,我们来看代码中的关键部分。`Page_Load`事件中,首先判断页面是否为首次加载(`!Page.IsPostBack...

    Bosket一个树视图组件库

    4. **产品目录**:电商平台中展示商品分类和子类目。 **总结** Bosket 作为一个强大的树视图组件库,通过其跨框架支持、高度可定制性和丰富的功能,极大地简化了开发者在构建树形结构界面时的工作。无论是简单的...

    vue-charts:echarts动态折线图

    data: data.map(item =&gt; item.category) // 类目数据 }, yAxis: { type: "value" // 数值轴 }, series: [ { name: "动态数据", type: "line", data: data.map(item =&gt; item.value), // 折线图数据 show...

    ECharts 数据集(dataset)

    总结来说,ECharts的数据集(dataset)提供了强大的数据管理和映射功能,它允许用户更灵活地组织和使用数据,使得在ECharts中创建复杂、多维度的图表变得更加便捷。通过熟练掌握dataset的使用,可以极大地提升...

    iOS UIButton扩大按钮响应区域的解决方法

    首先,我们来看第一种方法,即通过创建一个UIButton的类目(Category)来扩大按钮的响应区域。在Objective-C中,类目可以给已有的类添加新的方法,而不会影响原有的代码结构。这里我们创建一个名为`UIButton+...

    利用百度echarts实现图表功能简单入门示例【附源码下载】

    - **xAxis/yAxis**:分别设置横轴和纵轴,包括类型('value'表示数值轴,'category'表示类目轴)和数据。 - **series**:图表系列,定义了具体的图表类型(如'bar'表示柱状图),堆叠方式、数据和样式。 【示例代码...

    考研英语高频词汇汇总

    - **category** (n.):意为“种类”、“类目”,用于描述划分的类别。 - **classify** (v.):意为“分类”、“分等”,指将事物按照一定标准进行分类。 ##### 20. 引起与促进类词汇 - **induce** (v.):意为“引起...

Global site tag (gtag.js) - Google Analytics