当前位置: 移动技术网 > 移动技术>移动开发>IOS > iOS中UIAlertController设置自定义标题与内容的方法

iOS中UIAlertController设置自定义标题与内容的方法

2019年07月24日  | 移动技术网移动技术  | 我要评论

前言

相信大家都知道,uialertcontroller的标题和内容都是黑色的(对uialertcontroller不了解的朋友可以参考这篇文章),但是在很多场景下都需要修改他们的颜色,比如在输入错误时把提示信息变为红色,或者自定义标题的颜色,可是在公开的api接口中好像并没有对应的方法,那么我们应该怎么做呢?下面话不多说了,来一起看看详细的介绍:

第三方控件

第一种方法当然就是使用第三方的alert控件了,现在github上有着众多的alert控件(如sclalertview等),相信有很多都可以满足大家的需求,只要使用cocoapods添加添加第三方库就可以了。

kvc方法

但是也有一些人,不愿意去使用第三方库,而是想要使用系统的uialertcontroller,这样当然也是可以的。苹果公司并没有完全的封死对uialertcontroller的定制,而是修改为了使用kvc的方法进行定制。如果要自定义标题和内容,可以通过nsattributedstring把字体和颜色设置好,然后在通过kvc的方法进行设置,就可以了。

下面是一个示例代码和对应的截图:

- (void)testalert {
 uialertcontroller *alert = [uialertcontroller alertcontrollerwithtitle:nil message:nil preferredstyle:uialertcontrollerstylealert];
 [alert addaction:[uialertaction actionwithtitle:@"取消" style:uialertactionstylecancel handler:nil]];
 nsdictionary *titleattr = @{
  nsfontattributename:[uifont boldsystemfontofsize:20],
  nsforegroundcolorattributename:[uicolor greencolor]
  };
 nsattributedstring *attributedtitle = [[nsattributedstring alloc] initwithstring:@"测试有颜色标题" attributes:titleattr];
 [alert setvalue:attributedtitle forkey:@"attributedtitle"];

 nsdictionary *messageattr = @{
  nsfontattributename:[uifont systemfontofsize:12],
  nsforegroundcolorattributename:[uicolor redcolor]
  };
 nsattributedstring *attributedmessage = [[nsattributedstring alloc] initwithstring:@"测试有颜色文本" attributes:messageattr];
 [alert setvalue:attributedmessage forkey:@"attributedmessage"];
 [self presentviewcontroller:alert animated:yes completion:nil];
}

屏幕截图


关于自定义标题和内容就说这么些了,主要还是要看代码才能明白。

总结

以上就是这篇文章的全部内容了,本文还有许多不足,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网