KVC的应用

一: [iOS]改变UIAlertController的标题、内容的字体和颜色

在开发中,弹出框是必不可少的,通常情况下,我们只要弹出系统自带的弹出框就可以。but,在某些情况下,万恶的UI会要求你修改显示文字的大小、颜色,虽然系统自带有一种红色字体的UIAlertAction,但是这种Action并不能放在Cancel位置,所以,更多时候,需要我们自己修改文字字体和颜色。
我采用的方法是KVC:
正常情况下,我们配置出来的UIAlertController是这样的:

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"提示内容" preferredStyle:UIAlertControllerStyleAlert];
//    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"提示内容" preferredStyle:UIAlertControllerStyleActionSheet];

    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"Default" style:UIAlertActionStyleDefault handler:nil];
    UIAlertAction *destructiveAction = [UIAlertAction actionWithTitle:@"Destructive" style:UIAlertActionStyleDestructive handler:nil];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];

    [alertController addAction:defaultAction];
    [alertController addAction:destructiveAction];
    [alertController addAction:cancelAction];

    [self presentViewController:alertController animated:YES completion:nil];

代码里展示了系统提供的三种UIAlertAction,现在我们要对文字的字体和颜色进行设置:

  • 1: 标题和提示内容的文字设置
//修改title
  NSMutableAttributedString *alertControllerStr = [[NSMutableAttributedString alloc] initWithString:@"提示"];
  [alertControllerStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 2)];
  [alertControllerStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(0, 2)];
  if (alertController valueForKey:@"attributedTitle") {
      [alertController setValue:alertControllerStr forKey:@"attributedTitle"];
  }
  //修改message
  NSMutableAttributedString *alertControllerMessageStr = [[NSMutableAttributedString alloc] initWithString:@"提示内容"];
  [alertControllerMessageStr addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(0, 4)];
  [alertControllerMessageStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, 4)];
  if (alertController valueForKey:@"attributedMessage") {
      [alertController setValue:alertControllerMessageStr forKey:@"attributedMessage"];
  }
  • 2: 设置按钮文字,就拿取消按钮距离:
 //修改按钮
  if (cancelAction valueForKey:@"titleTextColor") {
      [cancelAction setValue:[UIColor redColor] forKey:@"titleTextColor"];
  }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,269评论 4 61
  • { 11、核心动画 需要签协议,但是系统帮签好 一、CABasicAnimation 1、创建基础动画对象 CAB...
    CYC666阅读 1,604评论 2 4
  • 应用场景: 可以用key访问到属性,某些情况下可以减少代码量。 kvo就是基于kvc实现的。 字典模型转换。 给私...
    开心一刻_阅读 799评论 0 1
  • 幸好,你在! 从小一直听着外婆讲父母的故事长大,外婆说在父母的眼里没什么事是过不去的坎,只要彼此健康存在,因为他们...
    下一项阅读 244评论 0 1