Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change UIAlertcontroller background Color

Ok so I have this alert that I am using and I want the background of it to be black not grey like it is. I have managed to change the colour of the text for the title and the message but not the background colour. Well to the desired colour I want. I have changed it to green blue and white, but not black. When I try to change it to black it turns grey. Any suggestions will help and be appreciated. I tried this here How to change the background color of the UIAlertController? and that is how I got to where I am now.

Here is what I have going now:

func showAlert(title:String, message:String) {

    //Set up for the title color
    let attributedString = NSAttributedString(string: title, attributes: [
        NSFontAttributeName : UIFont.systemFontOfSize(15), //your font here,
        NSForegroundColorAttributeName : UIColor.whiteColor()
        ])
    //Set up for the Message Color
    let attributedString2 = NSAttributedString(string: message, attributes: [
        NSFontAttributeName : UIFont.systemFontOfSize(15), //your font here,
        NSForegroundColorAttributeName : UIColor.whiteColor()
        ])

    let alert = UIAlertController(title: title,message: message, preferredStyle: .Alert)

    alert.setValue(attributedString, forKey: "attributedTitle")
    alert.setValue(attributedString2, forKey: "attributedMessage")
    //alert.view.tintColor = UIColor.whiteColor()
    let dismissAction = UIAlertAction(title: "Dismiss", style: .Destructive, handler: nil)
        alert.addAction(dismissAction)
    self.presentViewController(alert, animated: true, completion: nil)
    //set the color of the Alert
    let subview = alert.view.subviews.first! as UIView
    let alertContentView = subview.subviews.first! as UIView
    alertContentView.backgroundColor = UIColor.blackColor()
    //alertContentView.backgroundColor = UIColor.greenColor()
    //Changes is to a grey color :( 
    /*
    alertContentView.backgroundColor = UIColor(
        red: 0,
        green: 0,
        blue: 0,
        alpha: 1.0)
    //Also another Grey Color Not batman black
    */

    //alertContentView.backgroundColor = UIColor.blueColor()
    //turns into a purple



}
like image 474
MNM Avatar asked May 18 '16 08:05

MNM


1 Answers

Swift 4.1 :

This is the best way works for me :

func testAlert(){
    let alert = UIAlertController(title: "Let's See ..",message: "It Works!", preferredStyle: .alert)
    let dismissAction = UIAlertAction(title: "Dismiss", style: .default, handler: nil)

    // Accessing alert view backgroundColor :
    alert.view.subviews.first?.subviews.first?.subviews.first?.backgroundColor = UIColor.green

    // Accessing buttons tintcolor :
    alert.view.tintColor = UIColor.white

    alert.addAction(dismissAction)
    present(alert, animated: true, completion:  nil)
}

Test Image

like image 60
cs4alhaider Avatar answered Sep 16 '22 22:09

cs4alhaider