改变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"];
  }

效果如下:

这里写图片描述

至于里面的key值怎么得到的,过两天会写一篇文章来讲述。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值