Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: transparent background for UIViewAlertController

Tags:

ios

swift

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

like image 769
alexjrlewis Avatar asked Feb 21 '26 20:02

alexjrlewis


2 Answers

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
like image 52
MasDennis Avatar answered Feb 24 '26 11:02

MasDennis


You need to access the superview of the UIAlertController

alertView.view.superview?.backgroundColor = UIColor.clearColor()
like image 43
Alex Blair Avatar answered Feb 24 '26 09:02

Alex Blair