iOS 知识-常用小技巧大杂烩

  1. 获取磁盘总空间大小
    //磁盘总空间
  • (CGFloat)diskOfAllSizeMBytes{
    CGFloat size = 0.0;
    NSError *error;
    NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
    if (error) {

ifdef DEBUG

    NSLog(@"error: %@", error.localizedDescription);

endif

}else{
    NSNumber *number = [dic objectForKey:NSFileSystemSize];
    size = [number floatValue]/1024/1024;
}
return size;

}

  1. 获取磁盘可用空间大小
    //磁盘可用空间
  • (CGFloat)diskOfFreeSizeMBytes{
    CGFloat size = 0.0;
    NSError *error;
    NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
    if (error) {

ifdef DEBUG

    NSLog(@"error: %@", error.localizedDescription);

endif

}else{
    NSNumber *number = [dic objectForKey:NSFileSystemFreeSize];
    size = [number floatValue]/1024/1024;
}
return size;

}

  1. 获取指定路径下某个文件的大小
    //获取文件大小
  • (long long)fileSizeAtPath:(NSString *)filePath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:filePath]) return 0;
    return [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
    }

  1. 获取文件夹下所有文件的大小
    //获取文件夹下所有文件的大小
  • (long long)folderSizeAtPath:(NSString *)folderPath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *filesEnumerator = [[fileManager subpathsAtPath:folderPath] objectEnumerator];
    NSString *fileName;
    long long folerSize = 0;
    while ((fileName = [filesEnumerator nextObject]) != nil) {
    NSString *filePath = [folderPath stringByAppendingPathComponent:fileName];
    folerSize += [self fileSizeAtPath:filePath];
    }
    return folerSize;
    }

  1. 获取字符串(或汉字)首字母
    //获取字符串(或汉字)首字母
  • (NSString *)firstCharacterWithString:(NSString *)string{
    NSMutableString *str = [NSMutableString stringWithString:string];
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
    NSString *pingyin = [str capitalizedString];
    return [pingyin substringToIndex:1];
    }

  1. 将字符串数组按照元素首字母顺序进行排序分组
    //将字符串数组按照元素首字母顺序进行排序分组
  • (NSDictionary *)dictionaryOrderByCharacterWithOriginalArray:(NSArray *)array{
    if (array.count == 0) {
    return nil;
    }
    for (id obj in array) {
    if (![obj isKindOfClass:[NSString class]]) {
    return nil;
    }
    }
    UILocalizedIndexedCollation *indexedCollation = [UILocalizedIndexedCollation currentCollation];
    NSMutableArray *objects = [NSMutableArray arrayWithCapacity:indexedCollation.sectionTitles.count];
    //创建27个分组数组
    for (int i = 0; i < indexedCollation.sectionTitles.count; i++) {
    NSMutableArray *obj = [NSMutableArray array];
    [objects addObject:obj];
    }
    NSMutableArray *keys = [NSMutableArray arrayWithCapacity:objects.count];
    //按字母顺序进行分组
    NSInteger lastIndex = -1;
    for (int i = 0; i < array.count; i++) {
    NSInteger index = [indexedCollation sectionForObject:array[i] collationStringSelector:@selector(uppercaseString)];
    [[objects objectAtIndex:index] addObject:array[i]];
    lastIndex = index;
    }
    //去掉空数组
    for (int i = 0; i < objects.count; i++) {
    NSMutableArray *obj = objects[i];
    if (obj.count == 0) {
    [objects removeObject:obj];
    }
    }
    //获取索引字母
    for (NSMutableArray *obj in objects) {
    NSString *str = obj[0];
    NSString *key = [self firstCharacterWithString:str];
    [keys addObject:key];
    }
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:objects forKey:keys];
    return dic;
    }

//获取字符串(或汉字)首字母

  • (NSString *)firstCharacterWithString:(NSString *)string{
    NSMutableString *str = [NSMutableString stringWithString:string];
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
    NSString *pingyin = [str capitalizedString];
    return [pingyin substringToIndex:1];

  1. 获取当前时间
    //获取当前时间
    //format: @"yyyy-MM-dd HH:mm:ss"、@"yyyy年MM月dd日 HH时mm分ss秒"
  • (NSString *)currentDateWithFormat:(NSString *)format{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    return [dateFormatter stringFromDate:[NSDate date]];
    }

  1. 计算上次日期距离现在多久, 如 xx 小时前、xx 分钟前等
    /**
  • 计算上次日期距离现在多久
  • @param lastTime 上次日期(需要和格式对应)
  • @param format1 上次日期格式
  • @param currentTime 最近日期(需要和格式对应)
  • @param format2 最近日期格式
  • @return xx分钟前、xx小时前、xx天前
    */
  • (NSString *)timeIntervalFromLastTime:(NSString *)lastTime
    lastTimeFormat:(NSString *)format1
    ToCurrentTime:(NSString *)currentTime
    currentTimeFormat:(NSString *)format2{
    //上次时间
    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
    dateFormatter1.dateFormat = format1;
    NSDate *lastDate = [dateFormatter1 dateFromString:lastTime];
    //当前时间
    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init];
    dateFormatter2.dateFormat = format2;
    NSDate *currentDate = [dateFormatter2 dateFromString:currentTime];
    return [Utilities timeIntervalFromLastTime:lastDate ToCurrentTime:currentDate];
    }

  • (NSString *)timeIntervalFromLastTime:(NSDate *)lastTime ToCurrentTime:(NSDate *)currentTime{
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    //上次时间
    NSDate *lastDate = [lastTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:lastTime]];
    //当前时间
    NSDate *currentDate = [currentTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:currentTime]];
    //时间间隔
    NSInteger intevalTime = [currentDate timeIntervalSinceReferenceDate] - [lastDate timeIntervalSinceReferenceDate];

    //秒、分、小时、天、月、年
    NSInteger minutes = intevalTime / 60;
    NSInteger hours = intevalTime / 60 / 60;
    NSInteger day = intevalTime / 60 / 60 / 24;
    NSInteger month = intevalTime / 60 / 60 / 24 / 30;
    NSInteger yers = intevalTime / 60 / 60 / 24 / 365;

    if (minutes <= 10) {
    return @"刚刚";
    }else if (minutes < 60){
    return [NSString stringWithFormat: @"%ld分钟前",(long)minutes];
    }else if (hours < 24){
    return [NSString stringWithFormat: @"%ld小时前",(long)hours];
    }else if (day < 30){
    return [NSString stringWithFormat: @"%ld天前",(long)day];
    }else if (month < 12){
    NSDateFormatter * df =[[NSDateFormatter alloc]init];
    df.dateFormat = @"M月d日";
    NSString * time = [df stringFromDate:lastDate];
    return time;
    }else if (yers >= 1){
    NSDateFormatter * df =[[NSDateFormatter alloc]init];
    df.dateFormat = @"yyyy年M月d日";
    NSString * time = [df stringFromDate:lastDate];
    return time;
    }
    return @"";
    }

  1. 判断手机号码格式是否正确
    //判断手机号码格式是否正确
  • (BOOL)valiMobile:(NSString )mobile{
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobile.length != 11)
    {
    return NO;
    }else{
    /
    *
    * 移动号段正则表达式
    /
    NSString CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\d{8}|(1705)\d{7}$";
    /

    * 联通号段正则表达式
    /
    NSString CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\d{8}|(1709)\d{7}$";
    /

    * 电信号段正则表达式
    */
    NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\d{8}$";
    NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
    BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
    NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
    BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
    NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
    BOOL isMatch3 = [pred3 evaluateWithObject:mobile];

      if (isMatch1 || isMatch2 || isMatch3) {
          return YES;
      }else{
          return NO;
      }
    

    }
    }


  1. 判断邮箱格式是否正确
    //利用正则表达式验证
  • (BOOL)isAvailableEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
    }

  1. 将十六进制颜色转换为 UIColor 对象
    //将十六进制颜色转换为 UIColor 对象
  • (UIColor *)colorWithHexString:(NSString *)color{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
    return [UIColor clearColor];
    }
    // strip "0X" or "#" if it appears
    if ([cString hasPrefix:@"0X"])
    cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
    cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
    return [UIColor clearColor];
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    //r
    NSString *rString = [cString substringWithRange:range];
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
    }

  1. 对图片进行滤镜处理
    #pragma mark - 对图片进行滤镜处理
    // 怀旧 --> CIPhotoEffectInstant 单色 --> CIPhotoEffectMono
    // 黑白 --> CIPhotoEffectNoir 褪色 --> CIPhotoEffectFade
    // 色调 --> CIPhotoEffectTonal 冲印 --> CIPhotoEffectProcess
    // 岁月 --> CIPhotoEffectTransfer 铬黄 --> CIPhotoEffectChrome
    // CILinearToSRGBToneCurve, CISRGBToneCurveToLinear, CIGaussianBlur, CIBoxBlur, CIDiscBlur, CISepiaTone, CIDepthOfField
  • (UIImage *)filterWithOriginalImage:(UIImage *)image filterName:(NSString *)name{
    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage *inputImage = [[CIImage alloc] initWithImage:image];
    CIFilter *filter = [CIFilter filterWithName:name];
    [filter setValue:inputImage forKey:kCIInputImageKey];
    CIImage *result = [filter valueForKey:kCIOutputImageKey];
    CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];
    UIImage *resultImage = [UIImage imageWithCGImage:cgImage];
    CGImageRelease(cgImage);
    return resultImage;
    }

  1. 对图片进行模糊处理
    #pragma mark - 对图片进行模糊处理
    // CIGaussianBlur ---> 高斯模糊
    // CIBoxBlur ---> 均值模糊(Available in iOS 9.0 and later)
    // CIDiscBlur ---> 环形卷积模糊(Available in iOS 9.0 and later)
    // CIMedianFilter ---> 中值模糊, 用于消除图像噪点, 无需设置radius(Available in iOS 9.0 and later)
    // CIMotionBlur ---> 运动模糊, 用于模拟相机移动拍摄时的扫尾效果(Available in iOS 9.0 and later)
  • (UIImage *)blurWithOriginalImage:(UIImage *)image blurName:(NSString *)name radius:(NSInteger)radius{
    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage *inputImage = [[CIImage alloc] initWithImage:image];
    CIFilter *filter;
    if (name.length != 0) {
    filter = [CIFilter filterWithName:name];
    [filter setValue:inputImage forKey:kCIInputImageKey];
    if (![name isEqualToString:@"CIMedianFilter"]) {
    [filter setValue:@(radius) forKey:@"inputRadius"];
    }
    CIImage *result = [filter valueForKey:kCIOutputImageKey];
    CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];
    UIImage *resultImage = [UIImage imageWithCGImage:cgImage];
    CGImageRelease(cgImage);
    return resultImage;
    }else{
    return nil;
    }
    }

  1. 调整图片饱和度、亮度、对比度
    /**
  • 调整图片饱和度, 亮度, 对比度
  • @param image 目标图片
  • @param saturation 饱和度
  • @param brightness 亮度: -1.0 ~ 1.0
  • @param contrast 对比度

*/

  • (UIImage *)colorControlsWithOriginalImage:(UIImage *)image
    saturation:(CGFloat)saturation
    brightness:(CGFloat)brightness
    contrast:(CGFloat)contrast{
    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage *inputImage = [[CIImage alloc] initWithImage:image];
    CIFilter *filter = [CIFilter filterWithName:@"CIColorControls"];
    [filter setValue:inputImage forKey:kCIInputImageKey];

    [filter setValue:@(saturation) forKey:@"inputSaturation"];
    [filter setValue:@(brightness) forKey:@"inputBrightness"];
    [filter setValue:@(contrast) forKey:@"inputContrast"];

    CIImage *result = [filter valueForKey:kCIOutputImageKey];
    CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];
    UIImage *resultImage = [UIImage imageWithCGImage:cgImage];
    CGImageRelease(cgImage);
    return resultImage;
    }

  1. 创建一张实时模糊效果 View (毛玻璃效果)
    //Avilable in iOS 8.0 and later
  • (UIVisualEffectView *)effectViewWithFrame:(CGRect)frame{
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
    effectView.frame = frame;
    return effectView;
    }

  1. 全屏截图
    //全屏截图
  • (UIImage *)shotScreen{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIGraphicsBeginImageContext(window.bounds.size);
    [window.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
    }

  1. 截取一张 view 生成图片
    //截取view生成一张图片
  • (UIImage *)shotWithView:(UIView *)view{
    UIGraphicsBeginImageContext(view.bounds.size);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
    }

  1. 截取view中某个区域生成一张图片
    //截取view中某个区域生成一张图片
  • (UIImage *)shotWithView:(UIView *)view scope:(CGRect)scope{
    CGImageRef imageRef = CGImageCreateWithImageInRect([self shotWithView:view].CGImage, scope);
    UIGraphicsBeginImageContext(scope.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGRect rect = CGRectMake(0, 0, scope.size.width, scope.size.height);
    CGContextTranslateCTM(context, 0, rect.size.height);//下移
    CGContextScaleCTM(context, 1.0f, -1.0f);//上翻
    CGContextDrawImage(context, rect, imageRef);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGImageRelease(imageRef);
    CGContextRelease(context);
    return image;
    }

  1. 压缩图片到指定尺寸大小
    //压缩图片到指定尺寸大小
  • (UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size{
    UIImage *resultImage = image;
    UIGraphicsBeginImageContext(size);
    [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIGraphicsEndImageContext();
    return resultImage;
    }

  1. 压缩图片到指定文件大小
    //压缩图片到指定文件大小
  • (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size{
    NSData *data = UIImageJPEGRepresentation(image, 1.0);
    CGFloat dataKBytes = data.length/1000.0;
    CGFloat maxQuality = 0.9f;
    CGFloat lastData = dataKBytes;
    while (dataKBytes > size && maxQuality > 0.01f) {
    maxQuality = maxQuality - 0.01f;
    data = UIImageJPEGRepresentation(image, maxQuality);
    dataKBytes = data.length/1000.0;
    if (lastData == dataKBytes) {
    break;
    }else{
    lastData = dataKBytes;
    }
    }
    return data;
    }

  1. 获取设备 IP 地址

需要先引入下头文件:

Objective-C

1
2

import

import


//获取设备 IP 地址

  • (NSString *)getIPAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    success = getifaddrs(&interfaces);
    if (success == 0) {
    temp_addr = interfaces;
    while(temp_addr != NULL) {
    if(temp_addr->ifa_addr->sa_family == AF_INET) {
    if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
    }
    }
    temp_addr = temp_addr->ifa_next;
    }
    }
    freeifaddrs(interfaces);
    return address;
    }


  1. 判断字符串中是否含有空格
    + (BOOL)isHaveSpaceInString:(NSString *)string{
    NSRange _range = [string rangeOfString:@" "];
    if (_range.location != NSNotFound) {
    return YES;
    }else {
    return NO;
    }
    }

  1. 判断字符串中是否含有某个字符串
    + (BOOL)isHaveString:(NSString *)string1 InString:(NSString *)string2{
    NSRange _range = [string2 rangeOfString:string1];
    if (_range.location != NSNotFound) {
    return YES;
    }else {
    return NO;
    }
    }

  1. 判断字符串中是否含有中文
    + (BOOL)isHaveChineseInString:(NSString *)string{
    for(NSInteger i = 0; i < [string length]; i++){
    int a = [string characterAtIndex:i];
    if (a > 0x4e00 && a < 0x9fff) {
    return YES;
    }
    }
    return NO;
    }

  1. 判断字符串是否全部为数字
    + (BOOL)isAllNum:(NSString *)string{
    unichar c;
    for (int i=0; i c=[string characterAtIndex:i];
    if (!isdigit(c)) {
    return NO;
    }
    }
    return YES;
    }

  1. 绘制虚线
    /*
    ** lineFrame: 虚线的 frame
    ** length: 虚线中短线的宽度
    ** spacing: 虚线中短线之间的间距
    ** color: 虚线中短线的颜色
    */
  • (UIView *)createDashedLineWithFrame:(CGRect)lineFrame
    lineLength:(int)length
    lineSpacing:(int)spacing
    lineColor:(UIColor *)color{
    UIView *dashedLine = [[UIView alloc] initWithFrame:lineFrame];
    dashedLine.backgroundColor = [UIColor clearColor];
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayer setBounds:dashedLine.bounds];
    [shapeLayer setPosition:CGPointMake(CGRectGetWidth(dashedLine.frame) / 2, CGRectGetHeight(dashedLine.frame))];
    [shapeLayer setFillColor:[UIColor clearColor].CGColor];
    [shapeLayer setStrokeColor:color.CGColor];
    [shapeLayer setLineWidth:CGRectGetHeight(dashedLine.frame)];
    [shapeLayer setLineJoin:kCALineJoinRound];
    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:length], [NSNumber numberWithInt:spacing], nil]];
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, 0);
    CGPathAddLineToPoint(path, NULL, CGRectGetWidth(dashedLine.frame), 0);
    [shapeLayer setPath:path];
    CGPathRelease(path);
    [dashedLine.layer addSublayer:shapeLayer];
    return dashedLine;
    }


1,打印View所有子视图

po [[self view]recursiveDescription]

2,layoutSubviews调用的调用时机

* 当视图第一次显示的时候会被调用

  • 当这个视图显示到屏幕上了,点击按钮
  • 添加子视图也会调用这个方法
  • 当本视图的大小发生改变的时候是会调用的
  • 当子视图的frame发生改变的时候是会调用的
  • 当删除子视图的时候是会调用的

3,NSString过滤特殊字符

// 定义一个特殊字符的集合
NSCharacterSet set = [NSCharacterSet characterSetWithCharactersInString:
@"@/:;()¥「」"、[]{}#%-
+=|~<>$ۥ'@#$%&*()+'""];
// 过滤字符串的特殊字符
NSString *newString = [trimString stringByTrimmingCharactersInSet:set];

4,TransForm属性

//平移按钮
CGAffineTransform transForm = self.buttonView.transform;
self.buttonView.transform = CGAffineTransformTranslate(transForm, 10, 0);

//旋转按钮
CGAffineTransform transForm = self.buttonView.transform;
self.buttonView.transform = CGAffineTransformRotate(transForm, M_PI_4);

//缩放按钮
self.buttonView.transform = CGAffineTransformScale(transForm, 1.2, 1.2);

//初始化复位
self.buttonView.transform = CGAffineTransformIdentity;

5,去掉分割线多余15像素

首先在viewDidLoad方法加入以下代码:
if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
[self.tableView setSeparatorInset:UIEdgeInsetsZero];
}
if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
[self.tableView setLayoutMargins:UIEdgeInsetsZero];
}
然后在重写willDisplayCell方法

  • (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell
    forRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
    [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
    [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    }

6,计算方法耗时时间间隔
// 获取时间间隔 
  
 

define TICK CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();

define TOCK NSLog(@"Time: %f", CFAbsoluteTimeGetCurrent() - start)

7,Color颜色宏定义

// 随机颜色

define RANDOM_COLOR [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1]

// 颜色(RGB)

define RGBCOLOR(r, g, b) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1]

// 利用这种方法设置颜色和透明值,可不影响子视图背景色

define RGBACOLOR(r, g, b, a) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:(a)]

8,Alert提示宏定义

- (void)exitApplication {
AppDelegate *app = [UIApplication sharedApplication].delegate;
UIWindow *window = app.window;

[UIView animateWithDuration:1.0f animations:^{
    window.alpha = 0;
} completion:^(BOOL finished) {
    exit(0);
}];

}

9,NSArray 快速求总和 最大值 最小值 和 平均值

NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil];
CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];
CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue];
CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];
NSLog(@"%fn%fn%fn%f",sum,avg,max,min);

10修改Label中不同文字颜色

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[self editStringColor:self.label.text editStr:@"好" color:[UIColor blueColor]];
}

  • (void)editStringColor:(NSString *)string editStr:(NSString *)editStr color:(UIColor *)color {
    // string为整体字符串, editStr为需要修改的字符串
    NSRange range = [string rangeOfString:editStr];

    NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:string];

    // 设置属性修改字体颜色UIColor与大小UIFont
    [attribute addAttributes:@{NSForegroundColorAttributeName:color} range:range];

    self.label.attributedText = attribute;
    }

10,播放声音

#import
// 1.获取音效资源的路径
NSString *path = [[NSBundle mainBundle]pathForResource:@"pour_milk" ofType:@"wav"];
// 2.将路劲转化为url
NSURL *tempUrl = [NSURL fileURLWithPath:path];
// 3.用转化成的url创建一个播放器
NSError *error = nil;
AVAudioPlayer *play = [[AVAudioPlayer alloc]initWithContentsOfURL:tempUrl error:&error];
self.player = play;
// 4.播放
[play play];

11检测是否IPad Pro和其它设备型号

- (BOOL)isIpadPro
{
UIScreen *Screen = [UIScreen mainScreen];
CGFloat width = Screen.nativeBounds.size.width/Screen.nativeScale;
CGFloat height = Screen.nativeBounds.size.height/Screen.nativeScale;
BOOL isIpad =[[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad;
BOOL hasIPadProWidth = fabs(width - 1024.f) = 8.0)

12修改Tabbar Item的属性
// 修改标题位置
self.tabBarItem.titlePositionAdjustment = UIOffsetMake(0, -10);
// 修改图片位置
self.tabBarItem.imageInsets = UIEdgeInsetsMake(-3, 0, 3, 0);

// 批量修改属性
for (UIBarItem *item in self.tabBarController.tabBar.items) {
    [item setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
             [UIFont fontWithName:@"Helvetica" size:19.0], NSFontAttributeName, nil]
                        forState:UIControlStateNormal];
}

// 设置选中和未选中字体颜色
[[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];

//未选中字体颜色
[[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor greenColor]} forState:UIControlStateNormal];

//选中字体颜色
[[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor cyanColor]} forState:UIControlStateSelected];

12,NULL – nil – Nil – NSNULL的区别

* nil是OC的,空对象,地址指向空(0)的对象。对象的字面零值

  • Nil是Objective-C类的字面零值

  • NULL是C的,空地址,地址的数值是0,是个长整数

  • NSNull用于解决向NSArray和NSDictionary等集合中添加空值的问题


11,去掉BackBarButtonItem的文字
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)
forBarMetrics:UIBarMetricsDefault]

12,控件不能交互的一些原因

1,控件的userInteractionEnabled = NO
2,透明度小于等于0.01,aplpha
3,控件被隐藏的时候,hidden = YES
4,子视图的位置超出了父视图的有效范围,子视图无法交互,设置了。
5,需要交互的视图,被其他视图盖住(其他视图开启了用户交互)。

12,修改UITextField中Placeholder的文字颜色

[text setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
}

13,视图的生命周期

1、 alloc 创建对象,分配空间
2、 init (initWithNibName) 初始化对象,初始化数据
3、 loadView 从nib载入视图 ,除非你没有使用xib文件创建视图
4、 viewDidLoad 载入完成,可以进行自定义数据以及动态创建其他控件
5、 viewWillAppear视图将出现在屏幕之前,马上这个视图就会被展现在屏幕上了
6、 viewDidAppear 视图已在屏幕上渲染完成

1、viewWillDisappear 视图将被从屏幕上移除之前执行
2、viewDidDisappear 视图已经被从屏幕上移除,用户看不到这个视图了
3、dealloc 视图被销毁,此处需要对你在init和viewDidLoad中创建的对象进行释放.

viewVillUnload- 当内存过低,即将释放时调用;
viewDidUnload-当内存过低,释放一些不需要的视图时调用。

14,应用程序的生命周期

1,启动但还没进入状态保存 :

  • (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions

2,基本完成程序准备开始运行:

  • (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

3,当应用程序将要入非活动状态执行,应用程序不接收消息或事件,比如来电话了:

  • (void)applicationWillResignActive:(UIApplication *)application

4,当应用程序入活动状态执行,这个刚好跟上面那个方法相反:

  • (void)applicationDidBecomeActive:(UIApplication *)application

5,当程序被推送到后台的时候调用。所以要设置后台继续运行,则在这个函数里面设置即可:

  • (void)applicationDidEnterBackground:(UIApplication *)application

6,当程序从后台将要重新回到前台时候调用,这个刚好跟上面的那个方法相反:

  • (void)applicationWillEnterForeground:(UIApplication *)application

7,当程序将要退出是被调用,通常是用来保存数据和一些退出前的清理工作:

  • (void)applicationWillTerminate:(UIApplication *)application

15,判断view是不是指定视图的子视图
 BOOL isView = [textView isDescendantOfView:self.view];

16,判断对象是否遵循了某协议

if ([self.selectedController conformsToProtocol:@protocol(RefreshPtotocol)]) {
[self.selectedController performSelector:@selector(onTriggerRefresh)];
}

17,页面强制横屏

#pragma mark - 强制横屏代码

  • (BOOL)shouldAutorotate{
    //是否支持转屏
    return NO;
    }
  • (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    //支持哪些转屏方向
    return UIInterfaceOrientationMaskLandscape;
    }
  • (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    return UIInterfaceOrientationLandscapeRight;
    }
  • (BOOL)prefersStatusBarHidden{
    return NO;
    }

18,系统键盘通知消息

1、UIKeyboardWillShowNotification-将要弹出键盘
2、UIKeyboardDidShowNotification-显示键盘
3、UIKeyboardWillHideNotification-将要隐藏键盘
4、UIKeyboardDidHideNotification-键盘已经隐藏
5、UIKeyboardWillChangeFrameNotification-键盘将要改变frame
6、UIKeyboardDidChangeFrameNotification-键盘已经改变frame

19,关闭navigationController的滑动返回手势

self.navigationController.interactivePopGestureRecognizer.enabled = NO;

20,设置状态栏背景为任意的颜色
- (void)setStatusColor
{
UIView *statusBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, 20)];
statusBarView.backgroundColor = [UIColor orangeColor];
[self.view addSubview:statusBarView];
}

22,Label行间距

-(void)test{
NSMutableAttributedString *attributedString =
[[NSMutableAttributedString alloc] initWithString:self.contentLabel.text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:3];

//调整行间距       

[attributedString addAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:NSMakeRange(0, [self.contentLabel.text length])];
self.contentLabel.attributedText = attributedString;
}


23,UIImageView填充模式
@"UIViewContentModeScaleToFill", // 拉伸自适应填满整个视图
@"UIViewContentModeScaleAspectFit", // 自适应比例大小显示
@"UIViewContentModeScaleAspectFill", // 原始大小显示
@"UIViewContentModeRedraw", // 尺寸改变时重绘
@"UIViewContentModeCenter", // 中间
@"UIViewContentModeTop", // 顶部
@"UIViewContentModeBottom", // 底部
@"UIViewContentModeLeft", // 中间贴左
@"UIViewContentModeRight", // 中间贴右
@"UIViewContentModeTopLeft", // 贴左上
@"UIViewContentModeTopRight", // 贴右上
@"UIViewContentModeBottomLeft", // 贴左下
@"UIViewContentModeBottomRight", // 贴右下

24,宏定义检测block是否可用

#define BLOCK_EXEC(block, ...) if (block) { block(VA_ARGS); };
// 宏定义之前的用法
if (completionBlock) {
completionBlock(arg1, arg2);
}
// 宏定义之后的用法
BLOCK_EXEC(completionBlock, arg1, arg2);

25,Debug栏打印时自动把Unicode编码转化成汉字

// 有时候我们在xcode中打印中文,会打印出Unicode编码,还需要自己去一些在线网站转换,有了插件就方便多了。
DXXcodeConsoleUnicodePlugin 插件

26,设置状态栏文字样式颜色

[[UIApplication sharedApplication] setStatusBarHidden:NO];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

26,自动生成模型代码的插件


可自动生成模型的代码,省去写模型代码的时间
ESJsonFormat-for-Xcode

27,iOS中的一些手势

轻击手势(TapGestureRecognizer)
轻扫手势(SwipeGestureRecognizer)
长按手势(LongPressGestureRecognizer)
拖动手势(PanGestureRecognizer)
捏合手势(PinchGestureRecognizer)
旋转手势(RotationGestureRecognizer)

27,iOS 开发中一些相关的路径

模拟器的位置:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs

文档安装位置:
/Applications/Xcode.app/Contents/Developer/Documentation/DocSets

插件保存路径:
~/Library/ApplicationSupport/Developer/Shared/Xcode/Plug-ins

自定义代码段的保存路径:
~/Library/Developer/Xcode/UserData/CodeSnippets/
如果找不到CodeSnippets文件夹,可以自己新建一个CodeSnippets文件夹。

证书路径
~/Library/MobileDevice/Provisioning Profiles


28,获取 iOS 路径的方法
获取家目录路径的函数
NSString *homeDir = NSHomeDirectory();

获取Documents目录路径的方法
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];

获取Documents目录路径的方法
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [paths objectAtIndex:0];

获取tmp目录路径的方法:
NSString *tmpDir = NSTemporaryDirectory();

29,字符串相关操作

去除所有的空格
[str stringByReplacingOccurrencesOfString:@" " withString:@""]

去除首尾的空格
[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

  • (NSString *)uppercaseString; 全部字符转为大写字母
  • (NSString *)lowercaseString 全部字符转为小写字母

30, CocoaPods pod install/pod update更新慢的问题
pod install --verbose --no-repo-update
pod update --verbose --no-repo-update
如果不加后面的参数,默认会升级CocoaPods的spec仓库,加一个参数可以省略这一步,然后速度就会提升不少。

31,MRC和ARC混编设置方式

在XCode中targets的build phases选项下Compile Sources下选择 不需要arc编译的文件
双击输入 -fno-objc-arc 即可

MRC工程中也可以使用ARC的类,方法如下:
在XCode中targets的build phases选项下Compile Sources下选择要使用arc编译的文件
双击输入 -fobjc-arc 即可

32,把tableview里cell的小对勾的颜色改成别的颜色

_mTableView.tintColor = [UIColor redColor];

33,调整tableview的separaLine线的位置
tableView.separatorInset = UIEdgeInsetsMake(0, 100, 0, 0);

34,设置滑动的时候隐藏navigation bar

navigationController.hidesBarsOnSwipe = Yes

35,自动处理键盘事件,实现输入框防遮挡的插件
IQKeyboardManager
https://github.com/hackiftekhar/IQKeyboardManager

36,Quartz2D相关

图形上下是一个CGContextRef类型的数据。
图形上下文包含:
1,绘图路径(各种各样图形)
2,绘图状态(颜色,线宽,样式,旋转,缩放,平移)
3,输出目标(绘制到什么地方去?UIView、图片)

1,获取当前图形上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
2,添加线条
CGContextMoveToPoint(ctx, 20, 20);
3,渲染
CGContextStrokePath(ctx);
CGContextFillPath(ctx);
4,关闭路径
CGContextClosePath(ctx);
5,画矩形
CGContextAddRect(ctx, CGRectMake(20, 20, 100, 120));
6,设置线条颜色
[[UIColor redColor] setStroke];
7, 设置线条宽度
CGContextSetLineWidth(ctx, 20);
8,设置头尾样式
CGContextSetLineCap(ctx, kCGLineCapSquare);
9,设置转折点样式
CGContextSetLineJoin(ctx, kCGLineJoinBevel);
10,画圆
CGContextAddEllipseInRect(ctx, CGRectMake(30, 50, 100, 100));
11,指定圆心
CGContextAddArc(ctx, 100, 100, 50, 0, M_PI * 2, 1);
12,获取图片上下文
UIGraphicsGetImageFromCurrentImageContext();
13,保存图形上下文
CGContextSaveGState(ctx)
14,恢复图形上下文
CGContextRestoreGState(ctx)

37,屏幕截图

 // 1. 开启一个与图片相关的图形上下文
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size,NO,0.0);

// 2. 获取当前图形上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();

// 3. 获取需要截取的view的layer
[self.view.layer renderInContext:ctx];

// 4. 从当前上下文中获取图片
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

// 5. 关闭图形上下文
UIGraphicsEndImageContext();

// 6. 把图片保存到相册
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

37,左右抖动动画

//1, 创建核心动画
CAKeyframeAnimation *keyAnima = [CAKeyframeAnimation animation];

//2, 告诉系统执行什么动画。
keyAnima.keyPath = @"transform.rotation";
keyAnima.values = @[@(-M_PI_4 /90.0 * 5),@(M_PI_4 /90.0 * 5),@(-M_PI_4 /90.0 * 5)];

// 3, 执行完之后不删除动画
keyAnima.removedOnCompletion = NO;

// 4, 执行完之后保存最新的状态
keyAnima.fillMode = kCAFillModeForwards;

// 5, 动画执行时间
keyAnima.duration = 0.2;

// 6, 设置重复次数。
keyAnima.repeatCount = MAXFLOAT;

// 7, 添加核心动画
[self.iconView.layer addAnimation:keyAnima forKey:nil];


38,CALayer 的知识
CALayer 负责视图中显示内容和动画
UIView 负责监听和响应事件

创建UIView对象时,UIView内部会自动创建一个图层(既CALayer)
UIView本身不具备显示的功能,是它内部的层才有显示功能.

CALayer属性:
position 中点(由anchorPoint决定)
anchorPoint 锚点
borderColor 边框颜色
borderWidth 边框宽度
cornerRadius 圆角半径
shadowColor 阴影颜色
contents 内容
opacity 透明度
shadowOpacity 偏移
shadowRadius 阴影半径
shadowColor 阴影颜色
masksToBounds 裁剪

39,性能相关

1. 视图复用,比如UITableViewCell,UICollectionViewCell.

  1. 数据缓存,比如用SDWebImage实现图片缓存。
  2. 任何情况下都不能堵塞主线程,把耗时操作尽量放到子线程。
  3. 如果有多个下载同时并发,可以控制并发数。
  4. 在合适的地方尽量使用懒加载。
  5. 重用重大开销对象,比如:NSDateFormatter、NSCalendar。
  6. 选择合适的数据存储。
  7. 避免循环引用。避免delegate用retain、strong修饰,block可能导致循环引用,NSTimer也可能导致内存泄露等。
  8. 当涉及到定位的时候,不用的时候最好把定位服务关闭。因为定位耗电、流量。
  9. 加锁对性能有重大开销。
  10. 界面最好不要添加过多的subViews.
  11. TableView 如果不同行高,那么返回行高,最好做缓存。
  12. Viewdidload 里尽量不要做耗时操作。

40,验证身份证号码

//验证身份证号码

  • (BOOL)checkIdentityCardNo:(NSString)cardNo
    {
    if (cardNo.length != 18) {
    return NO;
    }
    NSArray
    codeArray = [NSArray arrayWithObjects:@"7",@"9",@"10",@"5",@"8",@"4",@"2",@"1",@"6",@"3",@"7",@"9",@"10",@"5",@"8",@"4",@"2", nil];
    NSDictionary* checkCodeDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1",@"0",@"X",@"9",@"8",@"7",@"6",@"5",@"4",@"3",@"2", nil] forKeys:[NSArray arrayWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil]];

    NSScanner* scan = [NSScanner scannerWithString:[cardNo substringToIndex:17]];

    int val;
    BOOL isNum = [scan scanInt:&val] && [scan isAtEnd];
    if (!isNum) {
    return NO;
    }
    int sumValue = 0;

    for (int i =0; i


41,响应者链条顺序
1> 当应用程序启动以后创建 UIApplication 对象

2> 然后启动“消息循环”监听所有的事件

3> 当用户触摸屏幕的时候, "消息循环"监听到这个触摸事件

4> "消息循环" 首先把监听到的触摸事件传递了 UIApplication 对象

5> UIApplication 对象再传递给 UIWindow 对象

6> UIWindow 对象再传递给 UIWindow 的根控制器(rootViewController)

7> 控制器再传递给控制器所管理的 view

8> 控制器所管理的 View 在其内部搜索看本次触摸的点在哪个控件的范围内(调用Hit test检测是否在这个范围内)

9> 找到某个控件以后(调用这个控件的 touchesXxx 方法), 再一次向上返回, 最终返回给"消息循环"

10> "消息循环"知道哪个按钮被点击后, 在搜索这个按钮是否注册了对应的事件, 如果注册了, 那么就调用这个"事件处理"程序。(一般就是执行控制器中的"事件处理"方法)

42,使用函数式指针执行方法和忽略performSelector方法的时候警告

不带参数的:
SEL selector = NSSelectorFromString(@"someMethod");
IMP imp = [_controller methodForSelector:selector];
void (*func)(id, SEL) = (void *)imp;
func(_controller, selector);

带参数的:
SEL selector = NSSelectorFromString(@"processRegion:ofView:");
IMP imp = [_controller methodForSelector:selector];
CGRect (*func)(id, SEL, CGRect, UIView *) = (void *)imp;
CGRect result = func(_controller, selector, someRect, someView);

忽略警告:

pragma clang diagnostic push

pragma clang diagnostic ignored "-Warc-performSelector-leaks"

[someController performSelector: NSSelectorFromString(@"someMethod")]

pragma clang diagnostic pop

如果需要忽视的警告有多处,可以定义一个宏:

define SuppressPerformSelectorLeakWarning(Stuff)

do {
_Pragma("clang diagnostic push")
_Pragma("clang diagnostic ignored "-Warc-performSelector-leaks"")
Stuff;
_Pragma("clang diagnostic pop")
} while (0)
使用方法:
SuppressPerformSelectorLeakWarning(
[_target performSelector:_action withObject:self]
);

43,UIApplication的简单使用

--------设置角标数字--------
//获取UIApplication对象
UIApplication *ap = [UIApplication sharedApplication];
//在设置之前, 要注册一个通知,从ios8之后,都要先注册一个通知对象.才能够接收到提醒.
UIUserNotificationSettings *notice =
[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];
//注册通知对象
[ap registerUserNotificationSettings:notice];
//设置提醒数字
ap.applicationIconBadgeNumber = 20;

--------设置联网状态--------
UIApplication *ap = [UIApplication sharedApplication];
ap.networkActivityIndicatorVisible = YES;

你可能感兴趣的:(iOS 知识-常用小技巧大杂烩)