常用代码合集

作者: 周小小小丶迪 | 来源:发表于2020-07-23 10:23 被阅读0次

1、禁止手机睡眠

[UIApplication sharedApplication].idleTimerDisabled = YES;

2、隐藏某行cell

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

// 如果是你需要隐藏的那一行,返回高度为0

    if(indexPath.row == YouWantToHideRow){

        return 0;

    }  return 44;

}

// 然后再你需要隐藏cell的时候调用

[self.tableView beginUpdates];

[self.tableView endUpdates];

3、禁用button高亮

button.adjustsImageWhenHighlighted = NO;

4、tableview遇到这种报错failed to obtain a cell from its dataSource

是因为你的cell被调用的早了。先循环使用了cell,后又创建cell。顺序错了

可能原因:1、xib的cell没有注册 2、内存中已经有这个cell的缓存了(也就是说通过你的cellId找到的cell并不是你想要的类型),这时候需要改下cell的标识

5、去除数组中重复的对象

NSArray *newArr = [oldArr valueForKeyPath:@“@distinctUnionOfObjects.self"];

6、动态修改ableView的tableHeaderView或者tableFooterView的高度

开发中如果要动态修改tableView的tableHeaderView或者tableFooterView的高度,需要给tableView重新设置,而不是直接更改高度。正确的做法是重新设置一下tableView.tableFooterView = 更改过高度的view。为什么?其实在iOS8以上直接改高度是没有问题的,在iOS8中出现了contentSize不准确的问题,这是解决办法。

7、collectionView的内容小于其宽高的时候是不能滚动的,设置可以滚动:

collectionView.alwaysBounceHorizontal = YES;

collectionView.alwaysBounceVertical = YES;

8、颜色转图片

+ (UIImage *)cl_imageWithColor:(UIColor *)color {

  CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);

  UIGraphicsBeginImageContext(rect.size);

  CGContextRef context = UIGraphicsGetCurrentContext();

  CGContextSetFillColorWithColor(context, [color CGColor]);

  CGContextFillRect(context, rect);

  UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

  UIGraphicsEndImageContext();

  return image;

}

9、view设置圆角

#define ViewBorderRadius(View, Radius, Width, Color)

[View.layer setCornerRadius:(Radius)];\

[View.layer setMasksToBounds:YES];\

[View.layer setBorderWidth:(Width)];\

[View.layer setBorderColor:[Color CGColor]] // view圆角

10、强/弱引用

#define WeakSelf(type)  __weak typeof(type) weak##type = type; // weak

#define StrongSelf(type)  __strong typeof(type) type = weak##type; // strong

11、由角度转换弧度

#define DegreesToRadian(x) (M_PI * (x) / 180.0)

12、由弧度转换角度

#define RadianToDegrees(radian) (radian*180.0)/(M_PI)

13、获取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;

}

14、清理app缓存

- (void)handleClearView {

    //删除两部分

    //1.删除 sd 图片缓存

    //先清除内存中的图片缓存

    [[SDImageCache sharedImageCache] clearMemory];

    //清除磁盘的缓存

    [[SDImageCache sharedImageCache] clearDisk];

    //2.删除自己缓存

    NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];

    [[NSFileManager defaultManager] removeItemAtPath:myCachePath error:nil];

}

15、几个常用权限判断

    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(@"没有相册权限");

        }

    }];

16、长按复制功能

- (void)viewDidLoad

{

    [self.view addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(pasteBoard:)]];

}

- (void)pasteBoard:(UILongPressGestureRecognizer *)longPress {

    if (longPress.state == UIGestureRecognizerStateBegan) {

        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];

        pasteboard.string = @"需要复制的文本";

    }

}

17、image拉伸

+ (UIImage *)resizableImage:(NSString *)imageName

{

    UIImage *image = [UIImage imageNamed:imageName];

    CGFloat imageW = image.size.width;

    CGFloat imageH = image.size.height;

    return [image resizableImageWithCapInsets:UIEdgeInsetsMake(imageH * 0.5, imageW * 0.5, imageH * 0.5, imageW * 0.5) resizingMode:UIImageResizingModeStretch];

}

18、JSON字符串转字典

+ (NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString {

    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];

    NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];

    return responseJSON;

}

19、画水印

// 画水印

- (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;

}

20、身份证号验证

- (BOOL)validateIdentityCard {

    BOOL flag;

    if (self.length <= 0) {

        flag = NO;

        return flag;

    }

    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";

    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];

    return [identityCardPredicate evaluateWithObject:self];

}

21、移除字符串中的空格和换行

+ (NSString *)removeSpaceAndNewline:(NSString *)str {

    NSString *temp = [str stringByReplacingOccurrencesOfString:@" " withString:@""];

    temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];

    temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];

    return temp;

}

22、判断字符串中是否有空格

+ (BOOL)isBlank:(NSString *)str {

    NSRange _range = [str rangeOfString:@" "];

    if (_range.location != NSNotFound) {

        //有空格

        return YES;

    } else {

        //没有空格

        return NO;

    }

}

22、获取一个视频的第一帧图片

    NSURL *url = [NSURL URLWithString:filepath];

    AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:url options:nil];

    AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1];

    generate1.appliesPreferredTrackTransform = YES;

    NSError *err = NULL;

    CMTime time = CMTimeMake(1, 2);

    CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:&err];

    UIImage *one = [[UIImage alloc] initWithCGImage:oneRef];

    return one;

23、获取视频的时长

+ (NSInteger)getVideoTimeByUrlString:(NSString *)urlString {

    NSURL *videoUrl = [NSURL URLWithString:urlString];

    AVURLAsset *avUrl = [AVURLAsset assetWithURL:videoUrl];

    CMTime time = [avUrl duration];

    int seconds = ceil(time.value/time.timescale);

    return seconds;

}

24、UILabel设置内边距

子类化UILabel,重写drawTextInRect方法

- (void)drawTextInRect:(CGRect)rect {

    // 边距,上左下右

    UIEdgeInsets insets = {0, 5, 0, 5};

    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];

}

25、UILabel设置文字描边

子类化UILabel,重写drawTextInRect方法

- (void)drawTextInRect:(CGRect)rect

{

    CGContextRef c = UIGraphicsGetCurrentContext();

    // 设置描边宽度

    CGContextSetLineWidth(c, 1);

    CGContextSetLineJoin(c, kCGLineJoinRound);

    CGContextSetTextDrawingMode(c, kCGTextStroke);

    // 描边颜色

    self.textColor = [UIColor redColor];

    [super drawTextInRect:rect];

    // 文本颜色

    self.textColor = [UIColor yellowColor];

    CGContextSetTextDrawingMode(c, kCGTextFill);

    [super drawTextInRect:rect];

}

26、在状态栏增加网络请求的菊花,类似safari加载网页的时候状态栏菊花

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

27、修改cell.imageView的大小

UIImage *icon = [UIImage imageNamed:@""];

CGSize itemSize = CGSizeMake(30, 30);

UIGraphicsBeginImageContextWithOptions(itemSize, NO ,0.0);

CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);

[icon drawInRect:imageRect];

cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

28、为一个view添加虚线边框

CAShapeLayer *border = [CAShapeLayer layer];

    border.strokeColor = [UIColor colorWithRed:67/255.0f green:37/255.0f blue:83/255.0f alpha:1].CGColor;

    border.fillColor = nil;

    border.lineDashPattern = @[@4, @2];

    border.path = [UIBezierPath bezierPathWithRect:view.bounds].CGPath;

    border.frame = view.bounds;

    [view.layer addSublayer:border];

29、UITextView中打开或禁用复制,剪切,选择,全选等功能

// 继承UITextView重写这个方法

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender

{

// 返回NO为禁用,YES为开启

    // 粘贴

    if (action == @selector(paste:)) return NO;

    // 剪切

    if (action == @selector(cut:)) return NO;

    // 复制

    if (action == @selector(copy:)) return NO;

    // 选择

    if (action == @selector(select:)) return NO;

    // 选中全部

    if (action == @selector(selectAll:)) return NO;

    // 删除

    if (action == @selector(delete:)) return NO;

    // 分享

    if (action == @selector(share)) return NO;

    return [super canPerformAction:action withSender:sender];

}

30、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];

}

相关文章

  • 常用代码合集

    1、禁止手机睡眠 [UIApplication sharedApplication].idleTimerDisab...

  • JavaScript常用API合集

    JavaScript常用API合集 本文分享了一些JavaScript常用的代码,有DOM操作、CSS操作、对象(...

  • PyTorch常用代码

    PyTorch 52.PyTorch常用代码段合集 - 科技猛兽的文章 - 知乎https://zhuanlan....

  • PyTorch常用代码段

    PyTorch常用代码段整理合集,建议收藏! https://mp.weixin.qq.com/s/AGpU4Pw...

  • js片段

    前端常用代码合集 声明:所有文章都是转载整理的,只是为了自己学习,方便自己观看,如有侵权,请立即联系我,谢谢~1....

  • 百度小程序教程,微信小程序教程,微信小程序开发模板汇总(2018

    摘要:微信小程序教程合集,微信小程序模板合集,微信小程序行业解决方案合集,微信小程序源代码合集,百度小程序教程合集...

  • RunLoop补充知识

    RunLoop知识合集如下图: CFRunLoop简化后的代码分析

  • 代码片段合集

    UIScrollView scroll change background color } }

  • xiaocms代码合集

    在xiao:list中判断第一条数据{xiao:if $key==0} xiao:list num =10 数量...

  • 「合集」VBS代码

    代码 (Code) 激活窗口 模拟输入 参考 基本键一般来说,要发送的按键都可以直接用该按键字符本身来表示发送字母...

网友评论

    本文标题:常用代码合集

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