Alert Box with Custom Color and Image to Alert View

Alert Box with custom color and image to Alert View

Welcome again folks, now  in this tutorial we are going to learn how to create a Custom alert view

So in this tutorial, we are going to make custom Alert.

First of all, let’s Start with basic Alert View :

The code for this Alert view for reusable use will be:




func alertDialog(msg : String){

        let alrt = UIAlertController(title: “Title2”, message: msg, preferredStyle: UIAlertControllerStyle.alert)

        let cancel = UIAlertAction(title: “OK”, style: UIAlertActionStyle.cancel) { (action) in

        }

        alrt.addAction(cancel)

        alrt.view.tintColor = UIColor.blue

        self.present(alrt, animated: true, completion: nil)

}

You might like:

  1. Tutorial for creating a Pop-up screen using Swift 3
  2. Tutorial to create “Tabs in Swift 3”
  3. Tutorial to create Grid View using Collection View in Swift 3





Now, whenever we need to call this AlertBox we just need to write this:

alertDialog(msg: “Message”)

Which will give the output as :

Now, what if we want this Grey little more colorful and embed a Logo of your company in it?

So here are the modifications that you should do in the existing code to make it more dynamic looking

func alertDialogWithImage(msg : String, Icon : UIImage) {

        let alrt = UIAlertController(title: ” “, message: msg, preferredStyle: UIAlertControllerStyle.alert)  

        let cancel = UIAlertAction(title: “Dismiss”, style: UIAlertActionStyle.cancel) { (action) in

        }

        alrt.addAction(cancel)

        let subview = (alrt.view.subviews.first?.subiews.first?.subviews.first!)! as UIView

        subview.backgroundColor = UIColor(red: (145/255.0), green: (200/255.0), blue: (0/255.0), alpha: 1.0)

        alrt.view.tintColor = UIColor.black

        let imageView = UIImageView(frame: CGRect(x: 120, y: 10, width: 35, height: 35))        

        imageView.image = Icon

        alrt.view.addSubview(imageView)

        self.present(alrt, animated: true, completion: nil)

}




And wherever you need to show this alert view you just need to call this line in your code

alertDialogWithImage(msg: “Custom message”, Icon:  YOUR LOGO)

I have used a logo of Twitter and on calling this line of code we will get the output as :

THAT’S ALL, YOU CAN CHOOSE WHATEVER COLOR YOU WANT

iOS_Screen iOS_Screen1

 


Article written and submitted by: Niket Singh

Leave a Reply

Your email address will not be published. Required fields are marked *