Search code examples
iosswiftuialertviewuialertviewcontroller

How to set custom ViewController as the content of UIAlertController in swift


I have custom ViewController and want to show it as alert. When i do it like below, my custom ViewController does not fill the entire content of the UIAlertController and scroll bar is shown. How to do that and also how to disable scrolling.

let alert : UIAlertController =  UIAlertController(title: nil, message: nil, preferredStyle: .alert)
alert.setValue(myCustomViewController, forKey: "contentViewController")
self.present(alert, animated: true) 

Solution

  • I don't think you can do that. You might consider presenting your custom view controller in such a way it resembles an alert controller. A tip is to play around with modalPresentationStyle of your custom view controller. With that you can make a semi-transparent backgrounded view controller that looks like an UIAlertController. For example:

    myCustomViewController.modalPresentationStyle = .overCurrentContext
    myCustomViewController.view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
    present(myCustomViewController, animated: true, completion: nil)