简体   繁体   中英

Why am I getting Nil Layout Anchor warning while presenting my custom UIAlert?

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM