ajrlewis
ajrlewis

Reputation: 3058

Swift: transparent background for UIViewAlertController

there are many answers on Stack Overflow about this but none seem to work. how do you make the background color of a UIAlertViewController truly clear?

i have at the moment:

let errorAlert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
let subview = errorAlert.view.subviews.first! as UIView
let alertContentView = subview.subviews.first! as UIView
alertContentView.backgroundColor = UIColor.clearColor()
errorAlert.view.backgroundColor = UIColor.clearColor()
showViewController(errorAlert, sender: self)

but the result is a kind of white tinted, transparent-ish background over the image... is there anyway to remove this tinted background?

enter image description here

Upvotes: 3

Views: 5011

Answers (2)

MasDennis
MasDennis

Reputation: 746

In order to achieve this the color of all subviews needs to be set to UIColor.clear. In addition, all UIVisualEffectView child views need to be removed. This can be accomplished by using a recursive function (Swift 4):

func clearBackgroundColor(of view: UIView) {
    if let effectsView = view as? UIVisualEffectView {
        effectsView.removeFromSuperview()
        return
    }

    view.backgroundColor = .clear        
    view.subviews.forEach { (subview) in
        clearBackground(of: subview)
    }
}

Call this right after creating the UIAlertController instance:

let alert = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
clearBackgroundColor(of: alert.view)

If you now want to change the appearance of the alert:

alert.view.layer.backgroundColor = UIColor.red.withAlphaComponent(0.6).cgColor
alert.view.layer.cornerRadius = 5

Upvotes: 3

Alex Blair
Alex Blair

Reputation: 614

You need to access the superview of the UIAlertController

alertView.view.superview?.backgroundColor = UIColor.clearColor()

Upvotes: 2

Related Questions