美文网首页
多年iOS开发经验总结(二)

多年iOS开发经验总结(二)

作者: sfandy | 来源:发表于2017-07-11 17:49 被阅读25次

    1、设置UILabel行间距

    NSMutableAttributedString* attrString = [[NSMutableAttributedString  alloc] initWithString:label.text];    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setLineSpacing:20];
    [attrString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, label.text.length)];      
    label.attributedText = attrString;
    

    2、当使用-performSelector:withObject:withObject:afterDelay:方法时,需要传入多参数问题

      // 方法一、// 把参数放进一个数组/字典,直接把数组/字典当成一个参数传过去,具体方法实现的地方再解析这个数组/字典
    NSArray * array =  [NSArray arrayWithObjects: @"first", @"second", nil];
    [self performSelector:@selector(fooFirstInput:) withObject: array afterDelay:15.0];
    
    // 方法二、// 使用NSInvocationSEL aSelector = NSSelectorFromString(@"doSoming:argument2:");
      NSInteger argument1 = 10;
      NSString *argument2 = @"argument2";    if([self respondsToSelector:aSelector]) {
        NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:aSelector]];
        [inv setSelector:aSelector];
        [inv setTarget:self];
        [inv setArgument:&(argument1) atIndex:2];
        [inv setArgument:&(argument2) atIndex:3];
        [inv performSelector:@selector(invoke) withObject:nil afterDelay:15.0];
    }
    

    3、UILabel显示不同颜色字体

    NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:label.text];
    [string addAttribute:NSForegroundColorAttributeName value:  [UIColor redColor] range:NSMakeRange(0,5)];
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)];
    label.attributedText = string;
    

    4、比较两个CGRect/CGSize/CGPoint是否相等

    if (CGRectEqualToRect(rect1, rect2)) { // 两个区域相等       
         // do some
    }     
     if (CGPointEqualToPoint(point1, point2)) { // 两个点相等     
         // do some
    }    
    if (CGSizeEqualToSize(size1, size2)) { // 两个size相等        
        // do some
    }
    

    5、比较两个NSDate相差多少小时

      NSDate* date1 = someDate; 
      NSDate* date2 = someOtherDate; 
      NSTimeInterval distanceBetweenDates = [date1 timeIntervalSinceDate:date2]; 
      double secondsInAnHour = 3600;// 除以3600是把秒化成小时,除以60得到结果为相差的分钟数
       NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;
    

    7、播放一张张连续的图片

    // 加入现在有三张图片分别为animate_1、animate_2、animate_3// 
    方法一
        imageView.animationImages = @[[UIImage imageNamed:@"animate_1"], [UIImage imageNamed:@"animate_2"], [UIImage imageNamed:@"animate_3"]];
    imageView.animationDuration = 1.0;
    // 方法二
        imageView.image = [UIImage animatedImageNamed:@"animate_" duration:1.0];
    // 方法二解释下,这个方法会加载animate_为前缀的,后边0-1024,也就是animate_0、animate_1一直到animate_1024
    

    8、加载gif图片

      推荐使用这个框架 [FLAnimatedImage](https://github.com/Flipboard/FLAnimatedImage)
    

    9、防止离屏渲染为image添加圆角

    // image分类
    - (UIImage *)circleImage
    {// NO代表透明
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 1);
    // 获得上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    // 添加一个圆
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    // 方形变圆形
    CGContextAddEllipseInRect(ctx, rect);
    // 裁剪
    CGContextClip(ctx);
    // 将图片画上去
    [self drawInRect:rect];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();return image;
    }

    14、判断两个rect是否有交叉

     if (CGRectIntersectsRect(rect1, rect2))
      {
      }
    

    16、将一个view保存为pdf格式

    - (void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
    {   
     NSMutableData *pdfData = [NSMutableData data];  
     UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);   
     UIGraphicsBeginPDFPage();    
    CGContextRef pdfContext = UIGraphicsGetCurrentContext();
    [aView.layer renderInContext:pdfContext];      
    UIGraphicsEndPDFContext();    
    NSArray* documentDirectories =   NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);    
    NSString* documentDirectory = [documentDirectories objectAtIndex:0];    
    NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];
    [pdfData writeToFile:documentDirectoryFilename atomically:YES];   
     NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);
    }
    

    19、保存UIImage到本地

    NSArray *paths =     NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image.png"];
    
    [UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
    

    20、键盘上方增加工具栏

    UIToolbar *keyboardDoneButtonView = [[UIToolbar alloc] init];
    [keyboardDoneButtonView sizeToFit];
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
                                                               style:UIBarButtonItemStyleBordered target:self
                                                              action:@selector(doneClicked:)];
    [keyboardDoneButtonView setItems:[NSArray arrayWithObjects:doneButton, nil]];
      txtField.inputAccessoryView = keyboardDoneButtonView;
    

    22、在image上绘制文字并生成新的image

    UIFont *font = [UIFont boldSystemFontOfSize:12];
    UIGraphicsBeginImageContext(image.size);
    [image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)];
    CGRect rect = CGRectMake(point.x, point.y, image.size.width, image.size.height);
    [[UIColor whiteColor] set];
    [text drawInRect:CGRectIntegral(rect) withFont:font]; 
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    29、动画修改label上的文字

    // 方法一

        CATransition *animation = [CATransition animation];
      animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
      animation.type = kCATransitionFade;
      animation.duration = 0.75;
      [self.label.layer addAnimation:animation forKey:@"kCATransitionFade"];    
      self.label.text = @"New";
      // 方法二
      [UIView transitionWithView:self.label
                      duration:0.25f
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:^{                        
                    self.label.text = @"Well done!";
    
                    } completion:nil];
          // 方法三
            [UIView animateWithDuration:1.0
                     animations:^{                         
                    self.label.alpha = 0.0f;                         
                    self.label.text = @"newText";      
                                       self.label.alpha = 1.0f;
                     }];
    

    35、获取手机RAM容量

    // 需要导入#import <mach/mach.h>
    mach_port_t host_port;   
     mach_msg_type_number_t host_size;    
    vm_size_t pagesize;
    
    host_port = mach_host_self();
    host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
    host_page_size(host_port, &pagesize);  
    vm_statistics_data_t vm_stat;   
     if (host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size) != KERN_SUCCESS) {
        NSLog(@"Failed to fetch vm statistics");
    }    /* Stats in bytes */
    natural_t mem_used = (vm_stat.active_count +
                          vm_stat.inactive_count +
                          vm_stat.wire_count) * pagesize;    natural_t mem_free = vm_stat.free_count * pagesize;    natural_t mem_total = mem_used + mem_free;
    NSLog(@"已用: %u 可用: %u 总共: %u", mem_used, mem_free, mem_total);
    

    相关文章

      网友评论

          本文标题:多年iOS开发经验总结(二)

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