How to change the background color of the UIAlertController?

前端 未结 10 1465
耶瑟儿~
耶瑟儿~ 2020-11-30 03:49

Due to strange behavior of UIActionSheet in iOS 8, I have implemented UIAlertController with UIAction as buttons in it. I would like to change the entire background of the U

10条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 04:40

    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.

提交回复
热议问题