可以通过一个简单的项目重现该问题,如下所示:
当用户单击导航栏上的 +
按钮时,代码会实例化并以操作表样式呈现 UIAlertController
。
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func buttonTapped(_ sender: Any) {
let actionSheet = UIAlertController(title: nil,
message: nil,
preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Create Income",
style: .default) { _ in
print("Income!") })
actionSheet.addAction(UIAlertAction(title: "Create Outcome",
style: .default) { _ in
print("Outcome!")})
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in })
self.present(actionSheet, animated: true, completion: nil)
}
}
用户界面正确显示。问题是当操作表出现时 Xcode 会发出以下自动布局警告:
2020-03-12 11:24:57.002113+0800 alertcontroler_test[12757:936231] [LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<NSLayoutConstraint:0x600002d11b30 UIView:0x7f851961c560.width == - 16 (active)>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600002d11b30 UIView:0x7f851961c560.width == - 16 (active)>
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.
当操作表显示时,我检查 Xcode 中的 UI 层次结构,发现一些 subview 后面带有感叹号:
我用谷歌搜索了这个问题,但没有发现有人报告类似的问题(即,当 UIAlertController
显示时出现自动布局警告)。我找到了一些有关如何在 UIViewAlertForUnsatisfiableConstraints()
上设置断点以及如何调试汇编代码的信息。但我认为这是 UIAlertController 的内部问题,并且我创建和呈现 UIAlertController 的方式是常见且典型的。有什么建议我应该做什么吗?
这是在最新版本的 Xcode (11.3.1) 和 iOS (13.3) 上找到的。如果我将样式更改为警报,问题就会消失。任何帮助将不胜感激。
最佳答案
这是一个 Apple 团队尚未修复的错误,该错误与动画相关的警报和操作表有关。您可以点击以下链接来验证这一点:-
UIAlertController's actionSheet gives constraint error on iOS 12.2 / 12.3
Swift default AlertViewController breaking constraints
解决方案是将动画值传递为 false,例如:-
controller.present(alertController, animated: false, completion: nil)
我展示了没有动画的 UIAlertController,并且警告消失了。
或者您可以尝试 stackoverflow 的链接之一中提到的解决方案:-
@IBAction func buttonTapped(_ sender: UIButton) {
...
self.present(alertController,animated: true,completion: nil)
alertController.view.subviews.flatMap({$0.constraints}).filter{ (one: NSLayoutConstraint)-> (Bool) in
return (one.constant < 0) && (one.secondItem == nil) && (one.firstAttribute == .width)
}.first?.isActive = false
}
关于ios - 呈现 UIAlertController (以操作表样式)导致神秘的自动布局警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60647478/