[英]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.我有一个自定义 UIAlert,我将内容视图控制器设置为我自己的自定义 VC。 The alert functions properly, but I keep getting this error: "A constraint factory method was passed a nil layout anchor".警报功能正常,但我不断收到此错误:“约束工厂方法传递了一个 nil 布局锚点”。 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.这可能是因为您在将父视图控制器(警报控制器)添加到视图层次结构之前设置了contentViewController
。
As you probably know if you use this hack, contentViewController
is a private property and you're not supposed to access / set it.您可能知道,如果您使用这个 hack, contentViewController
是一个私有属性,您不应该访问/设置它。 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
.如果您真的想使用它,我建议您按照Leo Nathan 的回答并将UIAlertController
子类UIAlertController
。 If you then assign your contentViewController
in viewDidLoad()
, everything should be set up properly, including the parent's layout anchors.如果然后在viewDidLoad()
分配contentViewController
,则应该正确设置所有内容,包括父级的布局锚点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.