使用Swift 4更改UIAlertController背景颜色以及文本字体和颜色

时间:2018-10-02 00:15:00

标签: swift xcode fonts colors uialertcontroller

我想更改警报控制器的背景以匹配游戏背景,文本字体以匹配游戏文本字体在这里是我正在使用的代码,但无法正常工作

    let alertController = UIAlertController(title: "Time Up!", message: "Your time is up! You got a score of \(point) points and your total coins now is \(totalPoints). You Can Do Better", preferredStyle: .alert)

            let restartAction = UIAlertAction(title: "Play Again!", style: .default, handler: nil)
            alertController.addAction(restartAction)

            alertController.view.tintColor = UIColor(red: 226, green: 158, blue: 152, alpha: 1.0 )
            alertController.view.backgroundColor = UIColor(red: 226, green: 158, blue: 152, alpha: 1.0)
            alertController.view.layer.cornerRadius = 15

            self.present(alertController, animated: true, completion: nil)

2 个答案:

答案 0 :(得分:0)

警报控制器是默认的iOS控制器。您可以创建自定义视图。添加标签,按钮并在其上应用颜色主题。

或者有第三方库,您可以使用它。

https://github.com/dinhquan/SwiftAlertView

https://github.com/Hamadakram/AlertView

答案 1 :(得分:-1)

在更改UIAlertController background color时,您需要这样做:

alertController.view
    .subviews.first?
    .subviews.first?
    .subviews.first?
    .backgroundColor = UIColor(red: 226/255.0, green: 158/255.0, blue: 152/255.0, alpha: 1.0)

在设置RGB UIColor时,还必须包含 / 255 才能起作用。示例:

UIColor(red: 226/255.0, green: 158/255.0, blue: 152/255.0, alpha: 1.0)