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

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

推荐阅读更多精彩内容