0

I have a custom UIAlert where I set the content view controller to my own custom VC. The alert functions properly, but I keep getting this error: "A constraint factory method was passed a nil layout anchor". I suspect it has something to do with how I am adding my subviews, but I have tried to constrain them to no avail. Here is the code:

    let vc = UIViewController()
    vc.preferredContentSize = CGSize(width: 250,height: 150)
    let sortByPicker = UIPickerView(frame: CGRect(x: 0, y: 0, width: 250, height: 150))
    sortByPicker.tag = 1
    sortByPicker.delegate = self
    sortByPicker.dataSource = self

    vc.view.addSubview(sortByPicker)

    let editRadiusAlert = UIAlertController(title: "Sort Projects By...", message: "", preferredStyle: UIAlertController.Style.alert)

    editRadiusAlert.setValue(vc, forKey: "contentViewController")
    editRadiusAlert.addAction(UIAlertAction(title: "Done", style: .default, handler: nil))
    editRadiusAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
    self.present(editRadiusAlert, animated: true)
Jeff Small
  • 91
  • 1
  • 5

1 Answers1

0

That's probably because you set your contentViewController before the parent view controller (the alert controller) has been added to the view hierarchy.

As you probably know if you use this hack, contentViewController is a private property and you're not supposed to access / set it. If you do so, you shouldn't be surprised if things don't work as expected or suddenly break in the future.

If you really wanna go with it, I suggest you follow Leo Nathan's answer and subclass UIAlertController. If you then assign your contentViewController in viewDidLoad(), everything should be set up properly, including the parent's layout anchors.

Mischa
  • 15,816
  • 8
  • 59
  • 117
  • I appreciate your input, I did not realize accessing a private API was a big no-no... but the more I read the more I am leaning away from tinkering with it. Is it true that Apple will reject app if I access a private API? – Jeff Small Feb 24 '20 at 20:15
  • As far as I know, if they figure it out → yes. But even if they didn't it's a bad practice because they can change / rename it anytime without you knowing and then you app might stop working / crashes. – Mischa Feb 24 '20 at 23:55
  • I decided to create a custom VC that mimics the alert VC. I really do appreciate it, I was overlooking this and I would've been distressed if it was rejected for this reason. – Jeff Small Feb 25 '20 at 00:28