iOS 开发总结(三)

总结一下常见的小问题.

1. 设置UILabel的行间距

  //设置图片行间距
  NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:label.text];
  NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
  style.lineSpacing = 10;
  [attribute addAttribute:NSParagraphStyleAttributeName value:style   range:NSMakeRange(0, label.text.length)];
  label.attributedText = attribute;
设置label间距

2.UILabel显示不同颜色字体

  //UILabel显示不同字体颜色
  NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:label.text];
  [attribute setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor]} range:NSMakeRange(0, 5)];
  [attribute setAttributes:@{NSForegroundColorAttributeName : [UIColor greenColor]} range:NSMakeRange(5, 3)];
  [attribute setAttributes:@{NSForegroundColorAttributeName : [UIColor orangeColor]} range:NSMakeRange(8, 5)];
  label.attributedText = attribute;

3. 比较两个CGRect/CGSize/CGPoint是否相等

  //比较两个CGRect/CGSize/CGPoint是否相等
  CGRect rect1 = CGRectMake(0, 0, 30, 40);
  CGRect rect2 = CGRectMake(0, 0, 20, 30);
  //CGSizeEqualToSize(<#CGSize size1#>, <#CGSize size2#>);
  //CGPointEqualToPoint(<#CGPoint point1#>, <#CGPoint point2#>)
  if (CGRectEqualToRect(rect1, rect2)) {
      NSLog(@"相等");
  }else{
      NSLog(@"不相等");
  }

4. 比较两个NSDate 相差多少小时

  //判断两个NSDate相差多少小时
  NSDate *date1 = someDate;
  NSDate *date2 = someOtherDate;
  NSTimeInterval timeInterval = [date1 timeIntervalSinceDate:date2];

5. 每个cell之间增加间距

方法一,每个分区只显示一行cell,分区头当作你想要的间距(注意,从数据源数组中取值的时候需要用indexPath.section而不是indexPath.row)

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{    
    return yourArry.count;
  }
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{    
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{    
    return cellSpacingHeight;
}

方法二,在cell的contentView上加个稍微低一点的view,cell上原本的内容放在你的view上,而不是contentView上,这样能伪造出一个间距来。
方法三,自定义cell,重写setFrame:方法

- (void)setFrame:(CGRect)frame{    
    frame.size.height -= 20;   
    [super setFrame:frame];
}

6. 播放一张张连续的图片

加入现在有三张图片分别为animate_1animate_2animate_3
// 方法一

  UIImageView *imageView;
  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

7. 加载gif图片

推荐使用这个框架 FLAnimatedImage

8. 查看系统所有字体

  for (id familyName in [UIFont familyNames]) {
      NSLog(@"%@", familyName);
      for (id fontName in [UIFont fontNamesForFamilyName:familyName]) {
          NSLog(@"---%@---", fontName);
      }
  }
运行结果

9. 判断一个字符串是否为数字

//判断一个字符串是否为数字
  NSString *str = @"452436535436";
  NSCharacterSet *notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
  if ([str rangeOfCharacterFromSet:notDigits].location == NSNotFound) {
      NSLog(@"是数字");
  }else{
      NSLog(@"不是数字");
  }

10. 让一个view在父视图的中心

  //让一个view在父视图的中心
  child.center = [parent convertPoint:parent.center fromView:parent.superview];

11. 保存图片

  • 保存图片到本地
  //将图片保存到本地
  UIImage *image = [UIImage imageNamed:@"aa.jpeg"];
  NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"image.jpeg"];
  [UIImageJPEGRepresentation(image, 1) writeToFile:path atomically:YES];
  • 保存图片到相册
  //将图片保存到相册
    /**
      *  将图片保存到iPhone本地相册
      *  UIImage *image            图片对象
      *  id completionTarget       响应方法对象
      *  SEL completionSelector    方法
      *  void *contextInfo
    */
  UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error == nil) {
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已存入手机相册" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
      [alert show];
    }else{  
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"保存失败" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
      [alert show];
    }  
}

12. 判断一个view是否是另一个view的子视图

  //判断一个view是否是另一个view的子视图
  UIView *view1;
  UIView *view2;
  BOOL isSon = [view1 isDescendantOfView:view2];

13. 导航控制器pop到指定viewController

  //导航控制器指定pop到指定的viewcontroller
  for (UIViewController *vc in self.navigationController.viewControllers) {
      if ([[vc isKindOfClass:[RequireViewController Class]]) {
          [self.navigationController popToViewController:vc animated:YES];
      }
  }

14. UITextView中显示html

  //UITextView中显示html
  UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(100, 200, 200, 150)];
  [self.view addSubview:textView];
  NSString *htmlString = @"<h1>Header</h1><h2>Subheader</h2><p>Some <em>text</em></p>![](http://upload-images.jianshu.io/upload_images/2370110-11fa1d3a2af409dd.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)";   
  NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType} documentAttributes:nil error:nil];
  textView.attributedText = attribute;

15. 隐藏UITextView/UITextField光标

  textField.tintColor = [UIColor clearColor];

16. 仿苹果🍎抖动动画

  self.backView = [[UIView alloc] initWithFrame:CGRectMake(100, 50, 50, 50)];
  self.backView.backgroundColor = [UIColor redColor];
  [self.view addSubview:self.backView];
  [self startAnimate];
  //    [self performSelector:@selector(stopAnimate) withObject:nil afterDelay:5];
//开始动画
- (void)startAnimate {
    self.backView.transform = CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(-5));
    [UIView animateWithDuration:0.25 delay:0.0 options:(UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse) animations:^ {
    self.backView.transform =      CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(5));
  } completion:nil];
}

//结束动画
- (void)stopAnimate {
    [UIView animateWithDuration:0.25 delay:0.0 options:(UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveLinear) animations:^{
        self.backView.transform = CGAffineTransformIdentity;
    } completion:nil];
}

17. 通知监听App生命周期

UIApplicationDidEnterBackgroundNotification 应用程序进入后台
UIApplicationWillEnterForegroundNotification 应用程序将要进入前台
UIApplicationDidFinishLaunchingNotification 应用程序完成启动
UIApplicationDidFinishLaunchingNotification 应用程序由挂起变的活跃
UIApplicationWillResignActiveNotification 应用程序挂起(有电话进来或者锁屏)
UIApplicationDidReceiveMemoryWarningNotification 应用程序收到内存警告
UIApplicationDidReceiveMemoryWarningNotification 应用程序终止(后台杀死、手机关机等)
UIApplicationSignificantTimeChangeNotification 当有重大时间改变(凌晨0点,设备时间被修改,时区改变等)
UIApplicationWillChangeStatusBarOrientationNotification 设备方向将要改变
UIApplicationDidChangeStatusBarOrientationNotification 设备方向改变
UIApplicationWillChangeStatusBarFrameNotification 设备状态栏frame将要改变
UIApplicationDidChangeStatusBarFrameNotification 设备状态栏frame改变
UIApplicationBackgroundRefreshStatusDidChangeNotification 应用程序在后台下载内容的状态发生变化
UIApplicationProtectedDataWillBecomeUnavailable 本地受保护的文件被锁定,无法访问
UIApplicationProtectedDataWillBecomeUnavailable 本地受保护的文件可用了

18. 触摸事件类型

UIControlEventTouchCancel 取消控件当前触发的事件
UIControlEventTouchDown 点按下去的事件
UIControlEventTouchDownRepeat 重复的触动事件
UIControlEventTouchDragEnter 手指被拖动到控件的边界的事件
UIControlEventTouchDragExit 一个手指从控件内拖到外界的事件
UIControlEventTouchDragInside 手指在控件的边界内拖动的事件
UIControlEventTouchDragOutside 手指在控件边界之外被拖动的事件
UIControlEventTouchUpInside 手指处于控制范围内的触摸事件
UIControlEventTouchUpOutside 手指超出控制范围的控制中的触摸事件

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

推荐阅读更多精彩内容