Willis
Willis

Reputation: 5336

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

Upvotes: 6

Views: 9457

Answers (3)

Shakeel Ahmed
Shakeel Ahmed

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

enter image description here

Upvotes: 9

Ariel Antonio Fundora
Ariel Antonio Fundora

Reputation: 1488

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

Upvotes: 3

CodeNoob
CodeNoob

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

Related Questions