【问题标题】:Why am I getting Nil Layout Anchor warning while presenting my custom UIAlert?为什么我在展示我的自定义 UIAlert 时收到 Nil Layout Anchor 警告?
【发布时间】:2020-06-08 11:46:35
【问题描述】:

我有一个自定义 UIAlert,我将内容视图控制器设置为我自己的自定义 VC。警报正常运行,但我不断收到此错误:“约束工厂方法传递了一个 nil 布局锚”。我怀疑这与我添加子视图的方式有关,但我试图限制它们无济于事。这是代码:

    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)

【问题讨论】:

    标签: ios swift autolayout nslayoutconstraint uialertcontroller


    【解决方案1】:

    这可能是因为您在将父视图控制器(警报控制器)添加到视图层次结构之前设置了 contentViewController

    您可能知道,如果您使用此 hack,contentViewController 是私有属性,您不应该访问/设置它。如果您这样做,那么如果事情没有按预期工作或将来突然中断,您不应该感到惊讶。

    如果你真的想用它,我建议你关注Leo Nathan's answer 和子类UIAlertController。如果您随后在viewDidLoad() 中分配您的contentViewController,则应正确设置所有内容,包括父级的布局锚点。

    【讨论】:

    • 感谢您的意见,我没有意识到访问私有 API 是一个很大的禁忌……但我阅读的越多,我就越倾向于远离修补它。如果我访问私有 API,Apple 是否会拒绝应用程序?
    • 据我所知,如果他们想通了 → 是的。但即使他们不这样做也是一种不好的做法,因为他们可以在您不知情的情况下随时更改/重命名它,然后您的应用程序可能会停止工作/崩溃。
    • 我决定创建一个模仿警报 VC 的自定义 VC。我真的很感激,我忽略了这一点,如果因为这个原因被拒绝,我会很痛苦。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    相关资源
    最近更新 更多