UIAlertController自定义字体,大小,颜色

我正在使用新的UIAlertController来显示警报。 我有这个代码:

// nil titles break alert interface on iOS 8.0, so we'll be using empty strings UIAlertController *alert = [UIAlertController alertControllerWithTitle: title == nil ? @"": title message: message preferredStyle: UIAlertControllerStyleAlert]; UIAlertAction *defaultAction = [UIAlertAction actionWithTitle: cancelButtonTitle style: UIAlertActionStyleCancel handler: nil]; [alert addAction: defaultAction]; UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController; [rootViewController presentViewController:alert animated:YES completion:nil]; 

现在我想改变标题和消息的字体,颜色,大小等等。 什么是最好的方法来做到这一点?

编辑:我应该插入整个代码。 我创build了UIView的类别,我可以显示正确的iOS版本警报。

 @implementation UIView (AlertCompatibility) +( void )showSimpleAlertWithTitle:( NSString * )title message:( NSString * )message cancelButtonTitle:( NSString * )cancelButtonTitle { float iOSVersion = [[UIDevice currentDevice].systemVersion floatValue]; if (iOSVersion < 8.0f) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle: title message: message delegate: nil cancelButtonTitle: cancelButtonTitle otherButtonTitles: nil]; [alert show]; } else { // nil titles break alert interface on iOS 8.0, so we'll be using empty strings UIAlertController *alert = [UIAlertController alertControllerWithTitle: title == nil ? @"": title message: message preferredStyle: UIAlertControllerStyleAlert]; UIAlertAction *defaultAction = [UIAlertAction actionWithTitle: cancelButtonTitle style: UIAlertActionStyleCancel handler: nil]; [alert addAction: defaultAction]; UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController; [rootViewController presentViewController:alert animated:YES completion:nil]; } } 

不知道这是否违反私人API /属性,但使用KVC在ios8上为我工作

 UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"Dont care what goes here, since we're about to change below" message:@"" preferredStyle:UIAlertControllerStyleActionSheet]; NSMutableAttributedString *hogan = [[NSMutableAttributedString alloc] initWithString:@"Presenting the great... Hulk Hogan!"]; [hogan addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:50.0] range:NSMakeRange(24, 11)]; [alertVC setValue:hogan forKey:@"attributedTitle"]; UIAlertAction *button = [UIAlertAction actionWithTitle:@"Label text" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){ //add code to make something happen once tapped }]; UIImage *accessoryImage = [UIImage imageNamed:@"someImage"]; [button setValue:accessoryImage forKey:@"image"]; 

对于logging,也可以使用这些私有API来更改警报操作的字体。 再次,它可能会让你的应用程序被拒绝,我还没有试图提交这样的代码。

 let alert = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) let action = UIAlertAction(title: "Some title", style: .Default, handler: nil) let attributedText = NSMutableAttributedString(string: "Some title") let range = NSRange(location: 0, length: attributedText.length) attributedText.addAttribute(NSKernAttributeName, value: 1.5, range: range) attributedText.addAttribute(NSFontAttributeName, value: UIFont(name: "ProximaNova-Semibold", size: 20.0)!, range: range) alert.addAction(action) presentViewController(alert, animated: true, completion: nil) // this has to be set after presenting the alert, otherwise the internal property __representer is nil guard let label = action.valueForKey("__representer")?.valueForKey("label") as? UILabel else { return } label.attributedText = attributedText 

您可以通过向UIAlertController应用色调来更改button的颜色。

在iOS 9上,如果窗口色调设置为自定义颜色,则必须在显示警报后立即应用色调颜色。 否则,色调将重置为您自定义的窗口色调颜色。

 // In your AppDelegate for example: window?.tintColor = UIColor.redColor() // Elsewhere in the App: let alertVC = UIAlertController(title: "Title", message: "message", preferredStyle: .Alert) alertVC.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) alertVC.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) // Works on iOS 8, but not on iOS 9 // On iOS 9 the button color will be red alertVC.view.tintColor = UIColor.greenColor() self.presentViewController(alert, animated: true, completion: nil) // Necessary to apply tint on iOS 9 alertVC.view.tintColor = UIColor.greenColor() 

您可以使用此代码更改button文本的颜色:

 alertC.view.tintColor = your color; 

也许这会帮助你。

@ dupuis2387答案的Swift翻译。 找出语法来设置UIAlertController标题的颜色和字体,通过KVC使用的attributedTitle标题键。

 let message = "Some message goes here." let alertController = UIAlertController( title: "", // This gets overridden below. message: message, preferredStyle: .Alert ) let okAction = UIAlertAction(title: "OK", style: .Cancel) { _ -> Void in } alertController.addAction(okAction) let fontAwesomeHeart = "\u{f004}" let fontAwesomeFont = UIFont(name: "FontAwesome", size: 17)! let customTitle:NSString = "I \(fontAwesomeHeart) Swift" // Use NSString, which lets you call rangeOfString() let systemBoldAttributes:[String : AnyObject] = [ // setting the attributed title wipes out the default bold font, // so we need to reconstruct it. NSFontAttributeName : UIFont.boldSystemFontOfSize(17) ] let attributedString = NSMutableAttributedString(string: customTitle as String, attributes:systemBoldAttributes) let fontAwesomeAttributes = [ NSFontAttributeName: fontAwesomeFont, NSForegroundColorAttributeName : UIColor.redColor() ] let matchRange = customTitle.rangeOfString(fontAwesomeHeart) attributedString.addAttributes(fontAwesomeAttributes, range: matchRange) alertController.setValue(attributedString, forKey: "attributedTitle") self.presentViewController(alertController, animated: true, completion: nil) 

在这里输入图像描述

在Xcode 8 Swift 3.0中

 @IBAction func touchUpInside(_ sender: UIButton) { let alertController = UIAlertController(title: "", message: "", preferredStyle: .alert) //to change font of title and message. let titleFont = [NSFontAttributeName: UIFont(name: "ArialHebrew-Bold", size: 18.0)!] let messageFont = [NSFontAttributeName: UIFont(name: "Avenir-Roman", size: 12.0)!] let titleAttrString = NSMutableAttributedString(string: "Title Here", attributes: titleFont) let messageAttrString = NSMutableAttributedString(string: "Message Here", attributes: messageFont) alertController.setValue(titleAttrString, forKey: "attributedTitle") alertController.setValue(messageAttrString, forKey: "attributedMessage") let action1 = UIAlertAction(title: "Action 1", style: .default) { (action) in print("\(action.title)") } let action2 = UIAlertAction(title: "Action 2", style: .default) { (action) in print("\(action.title)") } let action3 = UIAlertAction(title: "Action 3", style: .default) { (action) in print("\(action.title)") } let okAction = UIAlertAction(title: "Ok", style: .default) { (action) in print("\(action.title)") } alertController.addAction(action1) alertController.addAction(action2) alertController.addAction(action3) alertController.addAction(okAction) alertController.view.tintColor = UIColor.blue alertController.view.backgroundColor = UIColor.black alertController.view.layer.cornerRadius = 40 present(alertController, animated: true, completion: nil) } 

产量

UIAlertController自定义字体,大小和颜色

使用UIAppearance协议。 使用appearanceFont进行更多的操作来更改UIAlertAction字体。

UILabel创build一个类别

的UILabel + FontAppearance.h

 @interface UILabel (FontAppearance) @property (nonatomic, copy) UIFont * appearanceFont UI_APPEARANCE_SELECTOR; @end 

的UILabel + FontAppearance.m

 @implementation UILabel (FontAppearance) - (void)setAppearanceFont:(UIFont *)font { if (self.tag == 1001) { return; } BOOL isBold = (self.font.fontDescriptor.symbolicTraits & UIFontDescriptorTraitBold); const CGFloat* colors = CGColorGetComponents(self.textColor.CGColor); if (self.font.pointSize == 14) { // set font for UIAlertController title self.font = [UIFont systemFontOfSize:11]; } else if (self.font.pointSize == 13) { // set font for UIAlertController message self.font = [UIFont systemFontOfSize:11]; } else if (isBold) { // set font for UIAlertAction with UIAlertActionStyleCancel self.font = [UIFont systemFontOfSize:12]; } else if ((*colors) == 1) { // set font for UIAlertAction with UIAlertActionStyleDestructive self.font = [UIFont systemFontOfSize:13]; } else { // set font for UIAlertAction with UIAlertActionStyleDefault self.font = [UIFont systemFontOfSize:14]; } self.tag = 1001; } - (UIFont *)appearanceFont { return self.font; } @end 

用法:

[[UILabel appearanceWhenContainedIn:UIAlertController.class, nil] setAppearanceFont:nil];

AppDelegate.m中使其适用于所有的UIAlertController

使用UIAppearance协议。 设置字体的示例 – 创build一个类别来扩展UILabel

 @interface UILabel (FontAppearance) @property (nonatomic, copy) UIFont * appearanceFont UI_APPEARANCE_SELECTOR; @end @implementation UILabel (FontAppearance) -(void)setAppearanceFont:(UIFont *)font { if (font) [self setFont:font]; } -(UIFont *)appearanceFont { return self.font; } @end 

和它的用法:

 UILabel * appearanceLabel = [UILabel appearanceWhenContainedIn:UIAlertController.class, nil]; [appearanceLabel setAppearanceFont:[UIFont boldSystemFontOfSize:10]]; //for example 

testing并使用样式UIAlertControllerStyleActionSheet ,但我想它也可以与UIAlertControllerStyleAlert一起UIAlertControllerStyleAlert

PS更好地检查类的可用性,而不是iOS版本:

 if ([UIAlertController class]) { // UIAlertController code (iOS 8) } else { // UIAlertView code (pre iOS 8) } 

我正在使用它。

 [[UIView appearanceWhenContainedIn:[UIAlertController class], nil] setTintColor:[UIColor blueColor]]; 

添加一行(AppDelegate)并适用于所有UIAlertController。

呈现后在视图上设置色彩的颜色有问题; 即使在presentViewController:animated:completion:的完成块中执行此操作,也会对button标题的颜色产生闪烁效果。 这是草率的,不专业的,完全不能接受的。

提出的其他解决scheme取决于视图层次保持静态,这是苹果不愿意做的。 预计这些解决scheme将在未来的iOS版本中失败。

解决这个问题并在任何地方解决这个问题的方法之一就是通过向UIAlertController添加一个类别并调整viewWillAppear。

标题:

 // // UIAlertController+iOS9TintFix.h // // Created by Flor, Daniel J on 11/2/15. // #import <UIKit/UIKit.h> @interface UIAlertController (iOS9TintFix) + (void)tintFix; - (void)swizzledViewWillAppear:(BOOL)animated; @end 

执行:

 // // UIAlertController+iOS9TintFix.m // // Created by Flor, Daniel J on 11/2/15. // #import "UIAlertController+iOS9TintFix.h" #import <objc/runtime.h> @implementation UIAlertController (iOS9TintFix) + (void)tintFix { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ Method method = class_getInstanceMethod(self, @selector(viewWillAppear:)); Method swizzle = class_getInstanceMethod(self, @selector(swizzledViewWillAppear:)); method_exchangeImplementations(method, swizzle);}); } - (void)swizzledViewWillAppear:(BOOL)animated { [self swizzledViewWillAppear:animated]; for (UIView *view in self.view.subviews) { if (view.tintColor == self.view.tintColor) { //only do those that match the main view, so we don't strip the red-tint from destructive buttons. self.view.tintColor = [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0]; [view setNeedsDisplay]; } } } @end 

将.pch(预编译头文件)添加到您的项目并包含类别:

 #import "UIAlertController+iOS9TintFix.h" 

确保在项目中正确注册你的pch,并在每个使用UIAlertController的类中包含类别方法。

然后,在您的应用程序代表didFinishLaunchingWithOptions方法中,导入您的类别并调用

 [UIAlertController tintFix]; 

它会自动传播到您的应用程序中的每个UIAlertController实例,无论是由您的代码或其他人启动。

这个解决scheme适用于iOS 8.X和iOS 9.X,并且没有tint change post-presentation方法的闪烁。 对于UIAlertController的子视图的视图层次也是完全不可知的。

快乐的黑客!

解决scheme/对于iOS9的黑客

  UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Test Error" message:@"This is a test" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { NSLog(@"Alert View Displayed"); [[[[UIApplication sharedApplication] delegate] window] setTintColor:[UIColor whiteColor]]; }]; [alertController addAction:cancelAction]; [[[[UIApplication sharedApplication] delegate] window] setTintColor:[UIColor blackColor]]; [self presentViewController:alertController animated:YES completion:^{ NSLog(@"View Controller Displayed"); }]; 

我刚刚完成了对UIAlertController的replace。 这是唯一明智的做法,我想:


这里是我在Swift中的方法,它从这里获得了很多答案

 func changeAlert(alert: UIAlertController, backgroundColor: UIColor, textColor: UIColor, buttonColor: UIColor?) { let view = alert.view.firstSubview().firstSubview() view.backgroundColor = backgroundColor view.layer.cornerRadius = 10.0 // set color to UILabel font setSubviewLabelsToTextColor(textColor, view: view) // set font to alert via KVC, otherwise it'll get overwritten let titleAttributed = NSMutableAttributedString( string: alert.title!, attributes: [NSFontAttributeName:UIFont.boldSystemFontOfSize(17)]) alert.setValue(titleAttributed, forKey: "attributedTitle") let messageAttributed = NSMutableAttributedString( string: alert.message!, attributes: [NSFontAttributeName:UIFont.systemFontOfSize(13)]) alert.setValue(messageAttributed, forKey: "attributedMessage") // set the buttons to non-blue, if we have buttons if let buttonColor = buttonColor { alert.view.tintColor = buttonColor } } func setSubviewLabelsToTextColor(textColor: UIColor, view:UIView) { for subview in view.subviews { if let label = subview as? UILabel { label.textColor = textColor } else { setSubviewLabelsToTextColor(textColor, view: subview) } } } 

这在某些情况下是完美的,而在另外一些情况下则是完全失败的(颜色不像预期的那样)。

您可以使用像PMAlertController这样的外部库,而无需使用解决方法,您可以使用超级定制警报replaceApple的不可定制的UIAlertController。

与Xcode 8,Swift 3和Objective-C兼容

PMAlertController示例

特征:

  • [x]标题视图
  • [x]标题图像(可选)
  • [x]标题
  • [x]描述消息
  • [x]自定义:字体,颜色,尺寸等
  • [x] 1,2button(水平)或3 +button(垂直)
  • [x]按下button时closures
  • [x]文本字段支持
  • [x]与UIAlertController类似的实现
  • [x]椰子树
  • [x]迦太基
  • [x]使用UIKitanimation的animation
  • Objective-C的兼容性
  • [x] Swift 2.3和Swift 3支持

我为Urban Outfitters工作。 我们有一个开源的pod, URBNAlert ,我们在所有的应用程序中使用。 它基于UIAlertController ,但高度可定制。

来源在这里: https : //github.com/urbn/URBNAlert

或者通过将URBNAlert放置在URBNAlert中来简单安装

下面是一些示例代码:

 URBNAlertViewController *uac = [[URBNAlertViewController alloc] initWithTitle:@"The Title of my message can be up to 2 lines long. It wraps and centers." message:@"And the message that is a bunch of text. And the message that is a bunch of text. And the message that is a bunch of text."]; // You can customize style elements per alert as well. These will override the global style just for this alert. uac.alertStyler.blurTintColor = [[UIColor orangeColor] colorWithAlphaComponent:0.4]; uac.alertStyler.backgroundColor = [UIColor orangeColor]; uac.alertStyler.textFieldEdgeInsets = UIEdgeInsetsMake(0.0, 15.0, 0.0, 15.0); uac.alertStyler.titleColor = [UIColor purpleColor]; uac.alertStyler.titleFont = [UIFont fontWithName:@"Chalkduster" size:30]; uac.alertStyler.messageColor = [UIColor blackColor]; uac.alertStyler.alertMinWidth = @150; uac.alertStyler.alertMaxWidth = @200; // many more styling options available [uac addAction:[URBNAlertAction actionWithTitle:@"Ok" actionType:URBNAlertActionTypeNormal actionCompleted:^(URBNAlertAction *action) { // Do something }]]; [uac addAction:[URBNAlertAction actionWithTitle:@"Cancel" actionType:URBNAlertActionTypeCancel actionCompleted:^(URBNAlertAction *action) { // Do something }]]; [uac show]; 

请find这个类别。 我能够改变UIAlertAction和UIAlertController的字体和颜色。

使用:

 UILabel * appearanceLabel = [UILabel appearanceWhenContainedIn:UIAlertController.class, nil]; [appearanceLabel setAppearanceFont:yourDesireFont]]; 

有点笨重,但是现在我可以设置背景和文字颜色。 我在这里find了

 UIView * firstView = alertController.view.subviews.firstObject; UIView * nextView = firstView.subviews.firstObject; nextView.backgroundColor = [UIColor blackColor]; 

要将一个button(如CANCEL)的颜色更改为红色,可以使用这种名为UIAlertActionStyle.destructive的样式属性:

 let prompt = UIAlertController.init(title: "Reset Password", message: "Enter Your E-mail :", preferredStyle: .alert) let okAction = UIAlertAction.init(title: "Submit", style: .default) { (action) in //your code } let cancelAction = UIAlertAction.init(title: "Cancel", style: UIAlertActionStyle.destructive) { (action) in //your code } prompt.addTextField(configurationHandler: nil) prompt.addAction(okAction) prompt.addAction(cancelAction) present(prompt, animated: true, completion: nil); 

我创build了一个方法目标-C

 -(void)customAlertTitle:(NSString*)title message:(NSString*)message{ UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:nil cancelButtonTitle:@"NO" otherButtonTitles:@"YES", nil]; UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 80)]; UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 270, 50)]; titleLabel.text = title; titleLabel.font = [UIFont boldSystemFontOfSize:20]; titleLabel.numberOfLines = 2; titleLabel.textColor = [UIColor redColor]; titleLabel.textAlignment = NSTextAlignmentCenter; [subView addSubview:titleLabel]; UILabel *messageLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 30, 270, 50)]; messageLabel.text = message; messageLabel.font = [UIFont systemFontOfSize:18]; messageLabel.numberOfLines = 2; messageLabel.textColor = [UIColor redColor]; messageLabel.textAlignment = NSTextAlignmentCenter; [subView addSubview:messageLabel]; [alertView setValue:subView forKey:@"accessoryView"]; [alertView show]; } 

在Xcode 8.3.1上编码完美。 您可以根据要求定制。