Reputation: 5336
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:
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:
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
Upvotes: 6
Views: 9457
Reputation: 6021
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
Upvotes: 9
Reputation: 1488
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);
Upvotes: 3
Reputation: 250
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)
Upvotes: 1