常用代码合集

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

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,302评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,563评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,433评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,628评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,467评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,354评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,777评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,419评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,725评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,768评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,543评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,387评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,794评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,032评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,305评论 1 252
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,741评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,946评论 2 336