UIAlertController 修改字体颜色

24

这是我创建 UIAlertController 的代码:

    // Create the alert controller
    var alertController = UIAlertController(title: "Are you sure you want to call \(self.number)?", message: "", preferredStyle: .Alert)

    // Create the actions
    var okAction = UIAlertAction(title: "Call", style: UIAlertActionStyle.Default) {
        UIAlertAction in
        var url:NSURL = NSURL(string: "tel://\(self.number)")!
        UIApplication.sharedApplication().openURL(url)
    }

    var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
        UIAlertAction in

    }

    // Add the actions
    alertController.addAction(okAction)
    alertController.addAction(cancelAction)

    // Present the controller
    self.presentViewController(alertController, animated: true, completion: nil)

我无法弄清如何更改取消和通话操作的文本颜色。标题文本当前为黑色,取消和通话按钮为白色。我想使它们全部变为黑色,以提高可见性。有什么建议吗?谢谢!

10个回答

24

经过一些尝试和错误,我发现这个方法可行。希望这对未来的Swift新手有所帮助!

alertController.view.tintColor = UIColor.blackColor()

这在第一次弹出警告时对我起作用了。但是在点击按钮后,它们又改回了默认颜色。从我在其他地方阅读的内容来看,我认为这个问题可能是iOS 9中的新问题。 - peacetype
因为这在iOS 9中不起作用,所以这里有一个解决方案来设置UIAlertController按钮的tintColor:https://dev59.com/Yl8d5IYBdhLWcg3wxUjC#32636878 - peacetype

9
皮尤什的回答对我最有帮助,但是这里有一些针对Swift 3的调整以及分别更改标题和消息的方法。
标题:
alert.setValue(NSAttributedString(string: alert.message, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 29, weight: UIFontWeightMedium), NSForegroundColorAttributeName : UIColor.red]), forKey: "attributedTitle")

信息:

alert.setValue(NSAttributedString(string: alert.message, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 29, weight: UIFontWeightMedium), NSForegroundColorAttributeName : UIColor.red]), forKey: "attributedMessage")

字体大小大是因为我实际上需要在tvOS上使用,它在tvOS和iOS上都表现良好。


标题:alert.setValue(NSAttributedString(string: alert.title, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 29, weight: UIFontWeightMedium), NSForegroundColorAttributeName : UIColor.red]), forKey: "attributedTitle") - Asmita

8

Swift 4.2

一种做法是在UIAlertController上进行扩展,这样你的应用程序中所有的警报都将具有相同的色调颜色。但它会以红色显示破坏性操作。

 extension UIAlertController{
        open override func viewDidLayoutSubviews() {
            super.viewDidLayoutSubviews()
           self.view.tintColor = .yourcolor
        }
    }

7
下面的代码可以改变UIAlertView标题的颜色。
  let alert = UIAlertController(title: messageTitle, message: messageText, preferredStyle: UIAlertControllerStyle.Alert)

  alert.setValue(NSAttributedString(string: messageTitle, attributes: [NSFontAttributeName : UIFont.systemFontOfSize(17),NSForegroundColorAttributeName : UIColor.redColor()]), forKey: "attributedTitle")

  alert.addAction(UIAlertAction(title: buttonText, style: UIAlertActionStyle.Default, handler: nil))

  parent.presentViewController(alert, animated: true, completion: nil)

如果您想更改按钮颜色,请在当前视图控制器之后添加以下代码。
  alert.view.tintColor = UIColor.redColor()

3
以下是关于Swift 4的更新,以Cody的答案为基础:
为警告标题设置颜色:
alert.setValue(NSAttributedString(string: alert.title!, attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.medium), NSAttributedStringKey.foregroundColor : UIColor.blue]), forKey: "attributedTitle")

设置警报信息的颜色:
alert.setValue(NSAttributedString(string: alert.message, attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.Medium), NSAttributedStringKey.foregroundColor : UIColor.green]), forKey: "attributedMessage")

根据https://developer.apple.com/documentation/foundation/nsattributedstring/key,此内容与编程有关。

1
只需要一个修改,您在颜色示例中遗漏了.font - jbm

3
在Swift 5和XCode 11.1及更高版本中,警告标题的颜色为:
alert.setValue(NSAttributedString(string: alert.title!, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 25, weight: UIFont.Weight.medium), NSAttributedString.Key.foregroundColor : UIColor.red]), forKey: "attributedTitle")

警告信息的颜色:

alert.setValue(NSAttributedString(string: alert.message!, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 20,weight: UIFont.Weight.medium),NSAttributedString.Key.foregroundColor :UIColor.black]), forKey: "attributedMessage")

1
我曾经遇到同样的问题,花了很多时间尝试找到最佳方法来改变iOS 9和iOS 10+的颜色,因为它是以不同的方式实现的。
最终我为UIViewController创建了一个扩展。在扩展中,我添加了一个自定义函数,几乎等同于默认函数“present”,但执行颜色修复。这是我的解决方案。适用于Swift 3+,针对iOS 9及以上版本的项目:
extension UIViewController {
    /// Function for presenting AlertViewController with fixed colors for iOS 9
    func presentAlert(alert: UIAlertController, animated flag: Bool, completion: (() -> Swift.Void)? = nil){
        // Temporary change global colors
        UIView.appearance().tintColor = UIColor.red // Set here whatever color you want for text
        UIApplication.shared.keyWindow?.tintColor = UIColor.red // Set here whatever color you want for text

        //Present the controller
        self.present(alert, animated: flag, completion: {
            // Rollback change global colors
            UIView.appearance().tintColor = UIColor.black // Set here your default color for your application.
            UIApplication.shared.keyWindow?.tintColor = UIColor.black // Set here your default color for your application.
            if completion != nil {
                completion!()
            }
        })
    }
}

要使用此固定功能,您只需调用此函数而不是默认的 present 函数。例如:

self.presentAlert(alert: alert, animated: true)

相同的解决方案,但适用于UIActivityViewController:
extension UIViewController {
    /// Function for presenting UIActivityViewController with fixed colors for iOS 9 and 10+
    func presentActivityVC(vc: UIActivityViewController, animated flag: Bool, completion: (() -> Swift.Void)? = nil) {
        // Temporary change global colors for changing "Cancel" button color for iOS 9 and 10+
        if UIDevice.current.systemVersion.range(of: "9.") != nil {
            UIApplication.shared.keyWindow?.tintColor = ColorThemes.alertViewButtonTextColor
        } else {
            UILabel.appearance().textColor = ColorThemes.alertViewButtonTextColor
        }

        self.present(vc, animated: flag) {
            // Rollback for changing global colors for changing "Cancel" button color for iOS 9 and 10+
            if UIDevice.current.systemVersion.range(of: "9.") != nil {
                UIApplication.shared.keyWindow?.tintColor = ColorThemes.tintColor
            } else {
                UILabel.appearance().textColor = ColorThemes.textColorNormal
            }
            if completion != nil {
                completion!()
            }
        }
    }
}

我希望这能帮助到某些人,并节省大量时间。因为这样详细的回答并没有节省我的时间 :)


1
在iOS 9.0之前,您可以像这样简单地更改基础视图的tintColor
alertController.view.tintColor = UIColor.redColor()

然而,由于iOS 9中引入的一个漏洞,你只能做到以下两点:

  1. Change the app tintColor in the AppDelegate.

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
        self.window.tintColor = UIColor.redColor()
        return true
    }
    
  2. Reapply the color in the completion block.

    self.presentViewController(alert, animated: true, completion: {() -> Void in
        alert.tintColor = UIColor.redColor()
    })
    

请看我在这里的另一个答案:https://dev59.com/CJfga4cB1Zd3GeqPCeMN#37737212


1

试试这个

alert.setValue(NSAttributedString(string: alert.message, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 29, weight: UIFontWeightMedium), NSForegroundColorAttributeName : UIColor.red]), forKey: "attributedTitle")

0
func showAlertOnVC(title: String,btnTitle:String, btnSubTitle:String, message: String, VC: UIViewController? , getcompleted: @escaping((_ confrmation: Bool)-> ())) {
        guard let vc = VC  else {
            return
        }
        let alert = UIAlertController(title: title , message: message, preferredStyle: (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad )  ? .alert : .alert)
        
        alert.view.tintColor = UIColor.green
        let confirmBtn = UIAlertAction(title: btnTitle, style: .default, handler: {_ in
            getcompleted(true)
        })
        let cancelBtn = UIAlertAction(title: btnSubTitle, style: .cancel, handler: {_ in
            getcompleted(false)
        })
        cancelBtn.setValue(UIColor.red, forKey: "titleTextColor")
        alert.addAction(confirmBtn)
        alert.addAction(cancelBtn)
        vc.present(alert, animated: true, completion: nil)
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接