Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting background color for UIAlertController in Swift

I am using the new UIAlertController to implement an options menu of sorts for my application. I am trying to get the background color of the UIAlertController to match the theme of the rest of my application. The theme for my application is pretty simple, and consists of white text with a blue/grey background color for the toolbar and navigation bar, shown below:

enter image description here

However, I am having some trouble trying to get my UIAlertController to conform to this theme. I made the the following two calls to set the text and background color:

uiAlertController.view.backgroundColor = UIColor(red: CGFloat(.17255), green: CGFloat(.24314), blue: CGFloat(.31373), alpha: CGFloat(1.0))
uiAlertController.view.tintColor = UIColor.whiteColor()

This changed the UIAlertController to look like below:

enter image description here

The text was changed from the default blue system color to white, but the background color is not correct. I also tried modifying the specifying opacity (uiAlertController.view.opaque = true) but this did not help either. How do I go about setting the background color so it matches my navigation bar and toolbar? Thanks

like image 957
Willis Avatar asked Feb 13 '15 13:02

Willis


3 Answers

Setting background color for UIAlertController in Swift

All you have to do is this:

//Create your alert controller

...

// Setting background color

let backView = yourAlertController.view.subviews.last?.subviews.last
backView?.layer.cornerRadius = 10.0
backView?.backgroundColor = UIColor.yellowColor() 

self.presentViewController(yourAlertController, animated: true, completion: nil);
like image 44
Ariel Antonio Fundora Avatar answered Sep 20 '22 10:09

Ariel Antonio Fundora


for Swift 3 Xcode 8.2.1

let subview = (alert.view.subviews.first?.subviews.first?.subviews.first!)! as UIView

                subview.backgroundColor = UIColor(red: (145/255.0), green: (200/255.0), blue: (0/255.0), alpha: 1.0)

                alert.view.tintColor = UIColor.black

enter image description here

like image 89
Shakeel Ahmed Avatar answered Sep 19 '22 10:09

Shakeel Ahmed


I had this same issue. Turns out I needed to traverse the subview tree like so:

var subView = alertController.view.subviews.first as! UIView
var contentView = subView.subviews.first as! UIView
contentView.backgroundColor = UIColor(red: 233.0/255.0, green: 133.0/255.0, blue: 49.0/255.0, alpha: 1.0)
like image 36
CodeNoob Avatar answered Sep 21 '22 10:09

CodeNoob