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


117

我正在使用新的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];

现在,我想更改标题和消息的字体,颜色,大小等。最好的方法是什么?

编辑: 我应该插入整个代码。我为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];
    }
}

2
DISCLAIMER:对于正在阅读以下答案的任何人。苹果将​​拒绝您的应用程序。如果您倾向于使用任何私有Api。在下面的答案中,这是发生了什么..
Yash Bedi

Answers:


98

不知道这是否违反私有API /属性,但是在iOS8上使用KVC对我有效

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"];

作为记录,也可以使用这些专用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

对于XCode 10及更高版本中的Swift 4.2,现在的最后两行是:

guard let label = (action!.value(forKey: "__representer")as? NSObject)?.value(forKey: "label") as? UILabel else { return }
        label.attributedText = attributedText

6
工作正常 attributedTitle用于标题和attributedMessage消息。不知道这是否是最好的解决方案,但对我而言已经足够了。
Libor Zapletal

2
我们可以在UIAlertController按钮上添加什么定制?
Aanchal Chaurasia

1
谢谢!我有一个小问题-可以在属性tile和message中使用自定义字体和颜色UIAlertController。一个人怎么能做到UIAlertAction呢?
p0lAris

71
我希望你们中没有人计划将其发布到应用商店,因为它使用了私有API。说真的,我不知道为什么当这些答案不是真正的“答案”时,它们总是在Stackoverflow上被接受。这些是您可能会也可能不会在应用程序商店中发布而摆脱的黑客。
TheCodingArt '16

3
对于在应用程序商店上发布应用程序的情况,Apple允许使用某些私有api,但不应使用可能损害或影响用户系统/隐私的api。因此,仅由于这个原因,这个答案可能会被许多人接受。可能对应用程序商店没有影响。可以使用此工具的人确认他们的应用程序未被拒绝吗?
Mehul Thakkar

66

您可以通过将色调颜色应用于UIAlertController来更改按钮颜色。

在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()

20
为了明确起见,在显示控制器后设置tintColor既可在iOS 8和9上运行,因此无需两次设置。
arlomedia

感谢您对iOS版加入了斯威夫特的回答和解决此问题的9
peacetype

3
当我点击并向下拖动手指时,它将再次变为默认颜色。任何想法?
msmq

这确实是唯一的体面答案。
TheCodingArt '16

46

您可以使用以下代码更改按钮文本的颜色:

alertC.view.tintColor = your color;

也许这会对您有所帮助。


@esilver是否设法找到了适用于iOS9的解决方案?
2015年

1
我没有。我与Apple创建了一个错误报告,编号为22391695。
esilver 2015年

1
有关此的更多信息。看来,当您滚动一长串项目时,您触摸滚动的项目就会变成蓝色...
Bejil

3
在iOS9和9.1中的UIAlertController上,所有这些操作均不起作用。.不知道苹果公司正在做什么...每次调用警报控制器时都需要手动更改窗口色调,然后在处理程序中将其更改回。
Akhilesh Sharma 2015年

它的工作原理与iOS 9.3,除非你润色outiside:回来体系蓝
雷米Belzanti

35

在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自定义字体,大小和颜色


抱歉,这是启动。如果功能需要,我会通知您...
iOS

24

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

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)

在此处输入图片说明


3
那“确定”按钮呢?我们可以自定义它吗?
Hassan Taleb

@HassanTaleb我还没有找到自定义按钮的好方法。您可以tintColorview或上设置appearanceWhenContainedIn,但是一旦触摸它,色彩就会消失。仍在寻找答案。
罗伯特·陈

@AbdulMomenعبدالمؤمن您看到什么错误消息?该代码段假定已经设置了FontAwesome。
罗伯特·陈

1
@RobertChen要解决此问题,只需在:之后加上颜色self.presentViewController(alertController, animated: true, completion: nil),是否可以更改按钮“ OK”的字体?
哈桑·塔莱布

4
这不是私人API吗?
王敬涵

13

使用UIAppearance协议。设置字体的示例-创建要扩展的类别 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

经过测试并且可以使用样式UIAlertControllerStyleActionSheet,但是我想它也可以使用UIAlertControllerStyleAlert

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

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

它正在工作,但是通过这种方式,我不能为消息和标题设置不同的大小。
Libor Zapletal

这可行,但是当单击一个动作时,字体又恢复为原始大小了吗?这会发生在你身上吗?
拉里

我有同样的问题@Larry,但我还没有找到一种解决方法。
alasker

12

使用UIAppearance协议。进行更多appearanceFont修改以更改字体UIAlertAction

为创建一个类别 UILabel

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


iOS 8.3中的标题为13pt粗体,因此我将条件更改为if (self.font.pointSize == 13 && isBold) {
Andrew Raphael

您提到了更改的字体UIAlertAction。但据我所知,UIAlertAction不使用UILabel。它使用NSStringgithub.com/nst/iOS-Runtime-Headers/blob/…我不知道如何自定义字体NSString
Peacetype

UIAlertAction根本不是视图类。它是描述动作的抽象类。然后在UIAlertController内部生成视图本身。因此,您可以设置UIAlertController中包含的外观。
mangerlahn

12

雨燕5和5.1。创建一个单独的文件,并将UIAlertController自定义代码放在此处

import Foundation
import  UIKit

extension UIAlertController {

  //Set background color of UIAlertController
  func setBackgroudColor(color: UIColor) {
    if let bgView = self.view.subviews.first,
      let groupView = bgView.subviews.first,
      let contentView = groupView.subviews.first {
      contentView.backgroundColor = color
    }
  }

  //Set title font and title color
  func setTitle(font: UIFont?, color: UIColor?) {
    guard let title = self.title else { return }
    let attributeString = NSMutableAttributedString(string: title)//1
    if let titleFont = font {
      attributeString.addAttributes([NSAttributedString.Key.font : titleFont],//2
        range: NSMakeRange(0, title.utf8.count))
    }
    if let titleColor = color {
      attributeString.addAttributes([NSAttributedString.Key.foregroundColor : titleColor],//3
        range: NSMakeRange(0, title.utf8.count))
    }
    self.setValue(attributeString, forKey: "attributedTitle")//4
  }

  //Set message font and message color
  func setMessage(font: UIFont?, color: UIColor?) {
    guard let title = self.message else {
      return
    }
    let attributedString = NSMutableAttributedString(string: title)
    if let titleFont = font {
      attributedString.addAttributes([NSAttributedString.Key.font : titleFont], range: NSMakeRange(0, title.utf8.count))
    }
    if let titleColor = color {
      attributedString.addAttributes([NSAttributedString.Key.foregroundColor : titleColor], range: NSMakeRange(0, title.utf8.count))
    }
    self.setValue(attributedString, forKey: "attributedMessage")//4
  }

  //Set tint color of UIAlertController
  func setTint(color: UIColor) {
    self.view.tintColor = color
  }
}

现在执行任何操作显示警报

  func tapShowAlert(sender: UIButton) {
    let alertController = UIAlertController(title: "Alert!!", message: "This is custom alert message", preferredStyle: .alert)
    // Change font and color of title
    alertController.setTitle(font: UIFont.boldSystemFont(ofSize: 26), color: UIColor.yellow)
    // Change font and color of message
    alertController.setMessage(font: UIFont(name: "AvenirNextCondensed-HeavyItalic", size: 18), color: UIColor.red)
    // Change background color of UIAlertController
    alertController.setBackgroudColor(color: UIColor.black)
    let actnOk = UIAlertAction(title: "Ok", style: .default, handler: nil)
    let actnCancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
    alertController.addAction(actnOk)
    alertController.addAction(actnCancel)
    self.present(alertController, animated: true, completion: nil)
  }

结果

在此处输入图片说明


1
我们在这里访问任何私人Api吗?您是否发布了具有这些自定义警报属性的任何应用程序?
Yash Bedi

@YashBedi,它正在使用私有API,Apple可能会拒绝您的应用程序使用“非公共API”。不,我还没有发布任何应用程序。
Gurjinder Singh,

在Apple开发人员站点上提到了这一点->重要事项UIAlertController类旨在按原样使用,不支持子类化。此类的视图层次结构是私有的,不能修改。
Gurjinder Singh,

知道了,老板。谢谢。
Yash Bedi

@ Darkglow请提及错误。我能够使用
Swift

10

我在用

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

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


3
由于现在已弃用,请使用[[UIView外观WhenContainedInInstancesOfClasses:@ [[UIAlertController类]]] setTintColor:newColor]; 相反
彼得·约翰逊

8

斯威夫特4

标题上的自定义字体示例。其他组件(例如消息或操作)的操作相同。

    let titleAttributed = NSMutableAttributedString(
            string: Constant.Strings.cancelAbsence, 
            attributes: [NSAttributedStringKey.font:UIFont(name:"FONT_NAME",size: FONT_SIZE)]
    )

    let alertController = UIAlertController(
        title: "",
        message: "",
        preferredStyle: UIAlertControllerStyle.YOUR_STYLE
    )

    alertController.setValue(titleAttributed, forKey : "attributedTitle")
    present(alertController, animated: true, completion: nil)

5

这是Swift 4.1和Xcode 9.4.1的扩展:

extension UIAlertController{

func addColorInTitleAndMessage(color:UIColor,titleFontSize:CGFloat = 18, messageFontSize:CGFloat = 13){

    let attributesTitle = [NSAttributedStringKey.foregroundColor: color, NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: titleFontSize)]
    let attributesMessage = [NSAttributedStringKey.foregroundColor: color, NSAttributedStringKey.font: UIFont.systemFont(ofSize: messageFontSize)]
    let attributedTitleText = NSAttributedString(string: self.title ?? "", attributes: attributesTitle)
    let attributedMessageText = NSAttributedString(string: self.message ?? "", attributes: attributesMessage)

    self.setValue(attributedTitleText, forKey: "attributedTitle")
    self.setValue(attributedMessageText, forKey: "attributedMessage")

}}

4

我刚刚完成了的替换UIAlertController。我认为是唯一明智的选择:


这是我在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)
        }
    }
}

这在某些情况下可以完美地工作,而在另一些情况下则完全是失败的(色调未按预期显示)。


4

您可以使用外部库,例如PMAlertController而无需使用变通方法,在,可以用超级可自定义的警报代替Apple不可自定义的UIAlertController。

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

PMAlertController示例


特征:

  • [x]标头视图
  • [x]标头图片(可选)
  • [x]标题
  • [x]说明消息
  • [x]定制:字体,颜色,尺寸等
  • [x] 1、2个按钮(水平)或3+个按钮(垂直)
  • [x]按下按钮时关闭
  • [x]文本字段支持
  • [x]与UIAlertController类似的实现
  • [x]椰子足
  • [x]迦太基
  • [x]带有UIKit Dynamics的动画
  • [x] Objective-C兼容性
  • [x] Swift 2.3和Swift 3支持

当操作按钮中的文本较长时,PMAlertController是否允许自动换行?
zeeple '17

@zeeple认为操作按钮是UIButton的子类。像这样的东西 actionButton.titleLabel.lineBreakMode = NSLineBreakByWordWrapping很好用。
Paolo Musolino

3

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

提出的其他解决方案取决于视图层次结构保持静态,这是Apple讨厌的事情。希望这些解决方案在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的类中包含category方法。

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

[UIAlertController tintFix];

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

此解决方案适用于iOS 8.X和iOS 9.X,并且缺少演示后色调更改的闪烁。对于UIAlertController的子视图的视图层次结构,它也是完全不可知的。

骇客骇客!


大多数情况下,此解决方案有效。但是,在设备旋转时,色泽会恢复到原来的状态,直到喷水为止。
Dhiraj Gupta 2015年

Dhiraj,我只是在项目设置中再次明确测试了这一点,以探索您的发现,但我不同意。色调不会回到旋转时的状态。
ObiDan 2015年

在xcode 6.4和xcode 7.0上已验证功能。运行8.X和9.0所有版本的模拟器。如果需要,我将把项目放在github上。
ObiDan 2015年

好吧,您可以继续进行一个项目,但这就是我所看到的。它在iPad上也不起作用。根据你的方法混写的想法,不过,我能够使它发挥作用的交叉混合viewDidLayoutSubviews,虽然。
Dhiraj Gupta

如果您提出了一个项目,那么我可以使用viewDidLayoutSubviews毛细雨来提交拉取请求,这是我刚刚使用的最新版本的应用程序,并已提交给App Store,您可以看看吗?
Dhiraj Gupta

3

请找到这个类别。我可以更改FONT和UIAlertAction和UIAlertController的颜色。

用:

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

5
请在此处粘贴代码或使用不需要人们登录的服务
。– Sulthan

3

在Swift 4.1和Xcode 10中

//Displaying alert with multiple actions and custom font ans size
let alert = UIAlertController(title: "", message: "", preferredStyle: .alert)

let titFont = [NSAttributedStringKey.font: UIFont(name: "ArialHebrew-Bold", size: 15.0)!]
let msgFont = [NSAttributedStringKey.font: UIFont(name: "Avenir-Roman", size: 13.0)!]

let titAttrString = NSMutableAttributedString(string: "Title Here", attributes: titFont)
let msgAttrString = NSMutableAttributedString(string: "Message Here", attributes: msgFont)

alert.setValue(titAttrString, forKey: "attributedTitle")
alert.setValue(msgAttrString, forKey: "attributedMessage")

let action1 = UIAlertAction(title: "Action 1", style: .default) { (action) in
    print("\(String(describing: action.title))")
}

let action2 = UIAlertAction(title: "Action 2", style: .default) { (action) in
    print("\(String(describing: action.title))")
}

let okAction = UIAlertAction(title: "Ok", style: .default) { (action) in
    print("\(String(describing: action.title))")
}
alert.addAction(action1)
alert.addAction(action2)
alert.addAction(okAction)

alert.view.tintColor = UIColor.blue
alert.view.layer.cornerRadius = 40
// //If required background colour 
// alert.view.backgroundColor = UIColor.white

DispatchQueue.main.async(execute: {
    self.present(alert, animated: true)
})

您的答案需要更新,self.present(alertController, animated: true)或者self.present(alert, animated: true)
Yash Bedi

@Yash Bedi,谢谢你我更新了我的答案,请检查一次。
iOS

2

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

我试过了 请注意,一旦显示警报控制器,您将还原窗口色调设置。我在警报控制器上看到颜色重新切换回右侧。我相信一旦采取任何行动,就必须完成还原。
赫尔曼

感谢@Germán指出这一点。对代码进行了更改。我现在正在AlertAction中处理还原。.但是,是的,我同意也可以在解除处理程序中处理
Akhilesh Sharma

1

我在城市服装店工作。我们有一个开源pod,URBNAlert我们在所有应用程序中都使用过。它基于UIAlertController,但是高度可定制。

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

或者只是通过放置URBNAlert在Podfile中的Pod来安装

这里是一些示例代码:

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];

这是否支持ActionSheet样式?
丹佩

@Danpe并非如此,它纯粹是为Alerts ..话虽如此..如果您希望它在存储库上造成问题。这是我们之前讨论过增加支持的内容
RyanG '16

1

要将一个按钮的颜色(例如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);

1

对于iOS 9.0及更高版本,请在应用程序委托中使用此代码

[[UIView appearanceWhenContainedInInstancesOfClasses:@[[UIAlertController class]]] setTintColor:[UIColor redColor]];

1

斯威夫特5.0

let titleAttrString = NSMutableAttributedString(string: "This is a title", attributes: [NSAttributedString.Key.font: UIFont(name: "CustomFontName", size: 17) as Any])
let messageAttrString = NSMutableAttributedString(string: "This is a message", attributes: [NSAttributedString.Key.font: UIFont(name: "CustomFontName", size: 13) as Any])

alertController.setValue(titleAttrString, forKey: "attributedTitle")
alertController.setValue(messageAttrString, forKey: "attributedMessage")

0

有点笨拙,但这对我来说现在可以设置背景和文本颜色。我在这里找到的。

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

它确实适用于背景颜色,但它永远不会改变色调颜色,这让我有些困惑
Akhilesh Sharma 2015年

0

我创建了一种方法Objective-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上完美运行。您可以根据需要自定义。


0

我只是使用这种需求,貌似和系统有关,细节略有不同,所以我们... OC实现了Alert和Sheet弹出窗口的封装。

在日常开发中经常遇到需要向Alert添加数字或更改按钮颜色的情况,例如“简单”的需求,如今带来了与系统组件高度相似并能够完全满足定制包装组件的需求。

GitHub:https : //github.com/ReverseScale/RSCustomAlertView

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.