美文网首页
【OC】常用方法总结

【OC】常用方法总结

作者: Richard_Wei | 来源:发表于2017-06-30 11:16 被阅读0次
    <统一收起键盘>
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    <数组去重>
    NSArray *newArr = [oldArr valueForKeyPath:@“@distinctUnionOfObjects.self"];
    @distinctUnionOfObjects.self  表示比较对象
    @distinctUnionOfObjects.[key] 表示比较对象的任意keyboarded
    
    <修改textField的placeholder的字体颜色、大小>
    [textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
    [textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
    
    <给一个view截图>
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    <UIView背景颜色渐变>
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
    [self.view addSubview:view];
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = view.bounds;
    gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
    [view.layer insertSublayer:gradient atIndex:0];
    
    <为UIView某个角添加圆角>
    // 左上角和右下角添加圆角
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerBottomRight) cornerRadii:CGSizeMake(20, 20)];
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    view.layer.mask = maskLayer;
    
    <拿到当前正在显示的控制器>
    - (UIViewController *)getVisibleViewControllerFrom:(UIViewController*)vc {
        if ([vc isKindOfClass:[UINavigationController class]]) {
            return [self getVisibleViewControllerFrom:[((UINavigationController*) vc) visibleViewController]];
        }else if ([vc isKindOfClass:[UITabBarController class]]){
            return [self getVisibleViewControllerFrom:[((UITabBarController*) vc) selectedViewController]];
        } else {
            if (vc.presentedViewController) {
                return [self getVisibleViewControllerFrom:vc.presentedViewController];
            } else {
                return vc;
            }
        }
    }
    
    <tableViewCell分割线顶到头>
    - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
        [cell setSeparatorInset:UIEdgeInsetsZero];
        [cell setLayoutMargins:UIEdgeInsetsZero];
        cell.preservesSuperviewLayoutMargins = NO;
    }
    - (void)viewDidLayoutSubviews {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    <image添加倒影效果>
    - (void)setImageShadow {
        CGRect frame = self.frame;
        frame.origin.y += (frame.size.height + 1);
         
        UIImageView *reflectionImageView = [[UIImageView alloc] initWithFrame:frame];
        self.clipsToBounds = TRUE;
        reflectionImageView.contentMode = self.contentMode;
        [reflectionImageView setImage:self.image];
        reflectionImageView.transform = CGAffineTransformMakeScale(1.0, -1.0);
     
        CALayer *reflectionLayer = [reflectionImageView layer];
        CAGradientLayer *gradientLayer = [CAGradientLayer layer];
        gradientLayer.bounds = reflectionLayer.bounds;
        gradientLayer.position = CGPointMake(reflectionLayer.bounds.size.width / 2, reflectionLayer.bounds.size.height * 0.5);
        gradientLayer.colors = [NSArray arrayWithObjects:
                                                            (id)[[UIColor clearColor] CGColor],
                                                            (id)[[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.3] CGColor], nil];
        gradientLayer.startPoint = CGPointMake(0.5,0.5);
        gradientLayer.endPoint = CGPointMake(0.5,1.0);
        reflectionLayer.mask = gradientLayer;
        [self.superview addSubview:reflectionImageView];
    }
    
    <添加图片水印>
    // 画水印
    - (void) setImage:(UIImage *)image withWaterMark:(UIImage *)mark inRect:(CGRect)rect {
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.0)
        {
            UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0.0);
        }
        //原图
        [image drawInRect:self.bounds];
        //水印图
        [mark drawInRect:rect];
        UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        self.image = newPic;
    }
    
    <删除NSUserDefaults所有记录>
    //方法一
    NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
    [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];  
    //方法二  
    - (void)resetDefaults {   
      NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
         NSDictionary * dict = [defs dictionaryRepresentation];
         for (id key in dict) {
              [defs removeObjectForKey:key];
         }
          [defs synchronize];
     }
    // 方法三
    [[NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[[NSBundle mainBundle] bundleIdentifier]];
    
    <跳进app权限设置>
    if (UIApplicationOpenSettingsURLString != NULL) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:url];
    }
    
    <获取app缓存大小>
    - (CGFloat)getCachSize {
     
        NSUInteger imageCacheSize = [[SDImageCache sharedImageCache] getSize];
        // 获取自定义缓存大小
        // 用枚举器遍历 一个文件夹的内容
        // 1.获取 文件夹枚举器
        NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
        NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:myCachePath];
        __block NSUInteger count = 0;
        // 2.遍历
        for (NSString *fileName in enumerator) {
            NSString *path = [myCachePath stringByAppendingPathComponent:fileName];
            NSDictionary *fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
            //自定义所有缓存大小
            count += fileDict.fileSize;
        }
        // 得到是字节  转化为M
        CGFloat totalSize = ((CGFloat)imageCacheSize+count)/1024/1024;
        return totalSize;
    }   
    
    <清理app缓存>
    - (void)cleanAppCache {
        // 删除两部分
        // 1.删除 sd 图片缓存
        // 先清除内存中的图片缓存
        [[SDImageCache sharedImageCache] clearMemory];
        // 清除磁盘的缓存
        [[SDImageCache sharedImageCache] clearDisk];
        // 2.删除自己缓存
        NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
        [[NSFileManager defaultManager] removeItemAtPath:myCachePath error:nil];
    }
    
    <几个常用权限判断>
    - (void)checkAppAuthorization{
        if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
            NSLog(@"没有定位权限");
        }
        AVAuthorizationStatus statusVideo = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (statusVideo == AVAuthorizationStatusDenied) {
            NSLog(@"没有摄像头权限");
        }
        AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
        if (statusAudio == AVAuthorizationStatusDenied) {
            NSLog(@"没有录音权限");
        }
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusDenied) {
                NSLog(@"没有相册权限");
            }
        }];
    }
    
    <去除导航黑线>
    // Swift:
    navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
    navigationController?.navigationBar.shadowImage = UIImage()
    // OC:
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    
    <事件穿透到下一层视图>
    self.isUserInteractionEnabled = false
    

    相关文章

      网友评论

          本文标题:【OC】常用方法总结

          本文链接:https://www.haomeiwen.com/subject/nfzycxtx.html