Как установить пользовательский ViewController в качестве содержимого UIAlertController в Swift

У меня есть собственный ViewController и я хочу показать его как предупреждение. Когда я делаю это, как показано ниже, мой пользовательский ViewController не заполняет все содержимое UIAlertController, и отображается полоса прокрутки. Как это сделать, а также как отключить прокрутку.

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

2 ответа

Решение

Я не думаю, что вы можете сделать это. Вы можете рассмотреть возможность представления своего пользовательского контроллера представления таким образом, чтобы он напоминал контроллер предупреждений. Совет - поиграть с modalPresentationStyle вашего собственного контроллера представления. С этим вы можете сделать полупрозрачный фоновый контроллер вида, который выглядит как UIAlertController, Например:

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

Да, ты можешь.

Вот пример

      var content_view_height:CGFloat = 200
var ctrl = MyViewController()
var alert = UIAlertController()

alert.setValue(ctrl, forKey: "contentViewController")
ctrl.preferredContentSize.height = content_view_height
alert.preferredContentSize.height = content_view_height

// you have to adjust the Alert size so it's bigger than your custom Content View Controller
var alert_height:CGFloat = 350
let custom_alert_height:NSLayoutConstraint = NSLayoutConstraint(
                item: alert.view,
                attribute: NSLayoutConstraint.Attribute.height,
                relatedBy: NSLayoutConstraint.Relation.equal,
                toItem: nil,
                attribute: NSLayoutConstraint.Attribute.notAnAttribute,
                multiplier: 1,
                //constant: self.view.frame.height * 0.50 // e.g. half of current view
                constant: alert_height // fixed
        )

alert.view.addConstraint(custom_alert_height);
// then present it

Другие вопросы по тегам