Setting background color for UIAlertController in Swift

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

enter image description here

However, I am having some problems making my UIAlertController fit this topic. I made the following two calls to set the color of text and background:

 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 as shown below:

enter image description here

The text has been changed to the default blue system color to white, but the background color is incorrect. I also tried changing the given opacity ( uiAlertController.view.opaque = true ), but that didn't help either. How do I adjust the background color to match my navigation bar and toolbar? Thanks

+5
source share
3 answers

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

+7
source

Setting background color for UIAlertController in Swift

All you have to do is the following:

// Create your alert controller

...

// Set the 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); 
+1
source

I had the same problem. Turns out I needed to go through the subview tree like this:

 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) 
0
source

Source: https://habr.com/ru/post/1213321/


All Articles