objectivec 自定义字体

将自定义字体添加到app <br/> <br/> 1.将字体添加到字体文件夹<br/> 2.更新package.json <br/> 3.运行shell命令<br/> 4.检查字体系列名称的appDelegate

package
 "rnpm": {
    "assets": [
  "./assets/fonts/"
    ]
}
terminal
react-native link
AppDelegate.m
for (NSString* family in [UIFont familyNames])
{
  NSLog(@"%@", family);
  for (NSString* name in [UIFont fontNamesForFamilyName: family])
  {
    NSLog(@" %@", name);
  }
}

objectivec UIView的扩大点击区域

UIView的的范畴,扩大点击区域。但是对纵横框架有依赖。

UIViewXXKit.m
//  Copyright © 2019年 lixinxing. All rights reserved.
//

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface UIView (XXKit)

//扩大响应触摸事件区域
@property (nonatomic, assign) UIEdgeInsets xx_touchAreaInsets;

@end

NS_ASSUME_NONNULL_END


//  Copyright © 2019年 lixinxing. All rights reserved.
//

#import "UIView+XXKit.h"
#import <objc/runtime.h>
#import <Aspects/Aspects.h>

@implementation UIView (XXKit)

#pragma mark -
- (UIEdgeInsets)xx_touchAreaInsets {
    return [objc_getAssociatedObject(self, @selector(xx_touchAreaInsets)) UIEdgeInsetsValue];
}

- (void)setXx_touchAreaInsets:(UIEdgeInsets)xx_touchAreaInsets {
    NSValue *value = [NSValue valueWithUIEdgeInsets:xx_touchAreaInsets];
    objc_setAssociatedObject(self, @selector(xx_touchAreaInsets), value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    //Aspect框架可以只对单个实例进行方法替换,不会影响所有的实例。
    [self aspect_hookSelector:@selector(pointInside:withEvent:) withOptions:AspectPositionInstead usingBlock:^(id<AspectInfo> info, CGPoint point, UIEvent *event) {
        UIEdgeInsets touchAreaInsets = xx_touchAreaInsets;
        CGRect bounds = self.bounds;
        if (!UIEdgeInsetsEqualToEdgeInsets(touchAreaInsets, UIEdgeInsetsZero)) {
            bounds = CGRectMake(bounds.origin.x - touchAreaInsets.left,
                                bounds.origin.y - touchAreaInsets.top,
                                bounds.size.width + touchAreaInsets.left + touchAreaInsets.right,
                                bounds.size.height + touchAreaInsets.top + touchAreaInsets.bottom);
        }
        BOOL isConatin = CGRectContainsPoint(bounds, point);
        NSInvocation *invocation = info.originalInvocation;
        [invocation setReturnValue:&isConatin];
    } error:NULL];
}


@end

objectivec 异步绘制图片圆角并缓存

DrawInternetImageCornerRadius
#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface UIImageView (LX_CornerRadius)


/**
 异步加载图片,并将图片异步绘制圆角设置。 (高性能,回缓存圆角图片)

 @param url 资源地址
 @param placeholderImage 占位图
 */
- (void)lx_setCircleImageWithURL:(NSURL *)url
                placeholderImage:(UIImage *)placeholderImage;

- (void)lx_setImageWithURL:(NSURL *)url
          placeholderImage:(UIImage *)placeholderImage
              cornerRadius:(CGFloat)cornerRadius;

- (void)lx_setImageWithURL:(NSURL *)url
          placeholderImage:(UIImage *)placeholderImage
                   corners:(UIRectCorner)corners
               cornerRadius:(CGFloat)cornerRadius;

@end

NS_ASSUME_NONNULL_END

#import "UIImageView+LX_CornerRadius.h"
#import <UIImageView+WebCache.h>


@implementation UIImageView (LX_CornerRadius)


- (void)lx_setCircleImageWithURL:(NSURL *)url
                placeholderImage:(UIImage *)placeholderImage {
    [self lx_setImageWithURL:url placeholderImage:placeholderImage corners:UIRectCornerTopLeft | UIRectCornerTopRight | UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadius:self.frame.size.height / 2.0];
}


- (void)lx_setImageWithURL:(NSURL *)url
           placeholderImage:(UIImage *)placeholderImage
               cornerRadius:(CGFloat)cornerRadius {
    [self lx_setImageWithURL:url placeholderImage:placeholderImage corners:UIRectCornerTopLeft | UIRectCornerTopRight | UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadius:cornerRadius];
}


- (void)lx_setImageWithURL:(NSURL *)url
           placeholderImage:(UIImage *)placeholderImage
                    corners:(UIRectCorner)corners
               cornerRadius:(CGFloat)cornerRadius {
    
    NSString *key = [UIImageView lx_cacheKeyWithUrl:url corners:corners cornerRadius:cornerRadius];
    UIImage *lastPreviousCachedImage = [[SDImageCache sharedImageCache] imageFromCacheForKey:key];
    if (lastPreviousCachedImage) {
        self.image = lastPreviousCachedImage;
        return;
    }
    
    [self sd_setImageWithURL:url placeholderImage:placeholderImage completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        
        if (image) {
            CGRect bounds = self.bounds;
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                UIGraphicsBeginImageContextWithOptions(bounds.size, NO, 0);
                CALayer *layer = [[CALayer alloc] init];
                layer.bounds = bounds;
                layer.contentsGravity = kCAGravityResizeAspectFill;
                layer.contents = (__bridge id _Nullable)(image.CGImage);
                layer.contentsScale = [[UIScreen mainScreen] scale];
                UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bounds byRoundingCorners:corners cornerRadii:CGSizeMake(cornerRadius, cornerRadius)];
                CAShapeLayer *maskLayer = [CAShapeLayer new];
                maskLayer.frame = bounds;
                maskLayer.path = maskPath.CGPath;
                maskLayer.contentsScale = [[UIScreen mainScreen] scale];
                layer.mask = maskLayer;
                
                [layer renderInContext:UIGraphicsGetCurrentContext()];
                UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
                UIGraphicsEndImageContext();
                image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                
                [[SDImageCache sharedImageCache] storeImage:image forKey:key toDisk:YES completion:^{
                    DDLogInfo(@"异步绘制圆角图片 store success %@", url);
                }];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.image = image;
                });
            });
            
        } else {
            self.image = placeholderImage;
        }
    }];
}

+ (NSString *)lx_cacheKeyWithUrl:(NSURL *)url corners:(UIRectCorner)corners cornerRadius:(CGFloat)cornerRadius {
    NSString * str = [NSString stringWithFormat:@"%@#%@-%@", url.absoluteString, @(corners), @(cornerRadius)];
    return [str md5Str];
}


@end

objectivec 绘制标签列表(可异步)

DrawLabel
//将标签绘制为图片
- (UIImage *)tagsImagewithTagsList:(NSArray *)tagsList maxWidth:(CGFloat)maxWidth {
    UIColor *borderColor = [UIColor colorWithHexString:@"0xFFFFFF"];
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(maxWidth, 17), NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGFloat curX = 0;
    for (int i=0; i<tagsList.count; i++) {
        NSString *str = tagsList[i];
        CGFloat width = [str getWidthWithFont:self.tagsFont constrainedToSize:CGSizeMake(999, 30)];
        CGRect frame = CGRectMake(curX, 0, width + 20, 16);
        if (CGRectGetMaxX(frame) > maxWidth) { //防止标签占用过多内容
            break;
        }
        CALayer *layer = [[CALayer alloc] init];
        layer.bounds = frame;
        layer.borderColor = borderColor.CGColor;
        layer.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.2].CGColor;
        layer.borderWidth = 1.0 / [UIScreen mainScreen].scale;
        layer.cornerRadius = 8;
        layer.masksToBounds = YES;
        layer.allowsEdgeAntialiasing = YES;
        layer.magnificationFilter = kCAFilterNearest;
        [layer renderInContext:context];
        [self drawString:str verticallyInRect:frame withFont:self.tagsFont color:borderColor andAlignment:NSTextAlignmentCenter];
        curX  = CGRectGetMaxX(frame) + 6;
    };
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    return image;
}

- (void)drawString:(NSString *)str
  verticallyInRect:(CGRect)rect
          withFont:(UIFont *)font
             color:(UIColor *)color
      andAlignment:(NSTextAlignment)alignment {
    rect.origin.y = rect.origin.y + ((rect.size.height - [str sizeWithAttributes:@{NSFontAttributeName:font}].height) / 2);
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setAlignment:alignment];
    
    [str drawInRect:rect withAttributes:@{
                                          NSFontAttributeName              : font,
                                          NSForegroundColorAttributeName   : color,
                                          NSParagraphStyleAttributeName    : style
                                          }];
}

objectivec NSNull的分类,处理服务器返回空值问题

服务器返回的json里面,处理字典,数组,数字,结果返回的是空值的现象<br/>

json
#import <Foundation/Foundation.h>

/*
 服务器返回的json里面,处理字典、数组、数字,结果返回的是空值的现象
 */

@interface NSNull (InternalNullExtention)

@end


#import "NSNull+InternalNullExtention.h"

#define NSNullObjects @[@"",@0,@{},@[]]

@implementation NSNull (InternalNullExtention)

- (NSMethodSignature*)methodSignatureForSelector:(SEL)selector
{
    NSMethodSignature* signature = [super methodSignatureForSelector:selector];
    if (!signature) {
        
        for (NSObject *object in NSNullObjects) {
            signature = [object methodSignatureForSelector:selector];
            if (signature) {
                break;
            }
        }
        
    }
    return signature;
}

- (void)forwardInvocation:(NSInvocation *)anInvocation
{
    SEL aSelector = [anInvocation selector];
    
    for (NSObject *object in NSNullObjects) {
        if ([object respondsToSelector:aSelector]) {
            [anInvocation invokeWithTarget:object];
            return;
        }
    }
    
    [self doesNotRecognizeSelector:aSelector];
}


@end

objectivec uiview show hide

.m
[UIView transitionWithView:button
                  duration:0.4
                   options:UIViewAnimationOptionTransitionCrossDissolve
                animations:^{
                     button.hidden = YES;
                }
                completion:NULL];

objectivec 文字信号

.m
    [self.textFieldMobile.rac_textSignal subscribeNext:^(NSString *x) {
        self.model.mobile = x;
    }];

objectivec 确认

.m
/**
 * 确认操作
 */
- (void)confirm:(NSString *)message operation:(void (^)(void))operation {
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        if (operation) {
            operation();
        }
    }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {}];
    [alert addAction:defaultAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
    
}

objectivec 1_系统警报弹框.M

1_alert.m
 
     UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"标题" message:@"注释信息,没有就写nil" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"标题1" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"点击了按钮1,进入按钮1的事件");
        //textFields是一个数组,获取所输入的字符串
        NSLog(@"%@",alert.textFields.lastObject.text);
    }];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"点击了取消");
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
 
    

objectivec flashlight(手电筒)打开关闭

打开关闭系统手电筒。

.m
- (void) flashlight
{
    AVCaptureDevice *flashLight = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([flashLight isTorchAvailable] && [flashLight isTorchModeSupported:AVCaptureTorchModeOn])
    {
        BOOL success = [flashLight lockForConfiguration:nil];
        if (success) 
        {
            if ([flashLight isTorchActive]) {
                [flashLight setTorchMode:AVCaptureTorchModeOff];
            } else {
                [flashLight setTorchMode:AVCaptureTorchModeOn];
            }
            [flashLight unlockForConfiguration];
        }
    }
}