How to change the background color of the UIAlertController? How to change the background color of the UIAlertController? ios ios

How to change the background color of the UIAlertController?


You have to step some views deeper:

let subview = actionController.view.subviews.first! as UIViewlet alertContentView = subview.subviews.first! as UIViewalertContentView.backgroundColor = UIColor.blackColor()

And maybe you want to keep original corner radius:

 alertContentView.layer.cornerRadius = 5;

Sorry for the "Swifting" but i'm not familiar with Objective-C. I hope that's similar.

Of course it's also important to change the title color of the actions. Unfortunately I don't know, how to set the color of actions separately. But this is, how you change all button text colors:

actionController.view.tintColor = UIColor.whiteColor();

EDIT:

The corner radius of the UIAlertController has changed since this answer's been posted! Replace this:

 alertContentView.layer.cornerRadius = 5;

to this:

 actionContentView.layer.cornerRadius = 15


maybe you like the use the blur effect in the dark mode. Here is a very easy way to get this:

UIVisualEffectView.appearance(whenContainedInInstancesOf: [UIAlertController.classForCoder() as! UIAppearanceContainer.Type]).effect = UIBlurEffect(style: .dark)


I have found a hack-ish way of doing it. First you need an extension to allow you to search for the UIVisualEffectView inside the UIAlertController:

extension UIView{    func searchVisualEffectsSubview() -> UIVisualEffectView?    {        if let visualEffectView = self as? UIVisualEffectView        {            return visualEffectView        }        else        {            for subview in subviews            {                if let found = subview.searchVisualEffectsSubview()                {                    return found                }            }        }        return nil    }}

Important: You have to call this function after calling presentViewController, because only after loading the view controller that the visual effects view is inserted into place. Then you can change the effect associated with it to a dark blur effect:

self.presentViewController(actionController, animated: true, completion: nil)if let visualEffectView = actionController.view.searchVisualEffectsSubview(){    visualEffectView.effect = UIBlurEffect(style: .Dark)}

And this is the final result:

demo picture

I am honestly surprised myself how well it works! I think this is probably something Apple forgot to add. Also, I haven't yet passed an App through approval with this "hack" (it isn't a hack because we're only using public APIs), but I'm confident there won't be a problem.


matomo