当视图布局不明确时,如何让我的 iOS 应用程序崩溃?

How can I make my iOS app crash when a view is laid out ambiguously?

我想通知我团队中的开发人员,并防止他们在创建具有不明确约束的视图时采取进一步行动。为此,我想让 phone 崩溃(在调试中)。我可以定期轮询以查看层次结构中是否有任何视图将 hasAmbiguousLayout 设置为 true,但这不是很好。但是,看起来 iOS 在其运行时问题区域中报告了不明确的布局。因此,对于不明确的布局,必须有一些等价于 UIViewAlertForUnsatisfiableConstraints 的东西。我怎样才能让它崩溃?

混合 UIViewController.viewDidLayoutSubviewsUIView.layoutSubviews 并断言 !hasAmbiguousLayout == false

这是一个游乐场示例:

import UIKit
import PlaygroundSupport

extension UIViewController {
  @objc private func swizzledViewDidLayoutSubviews() {
    assert(!view.hasAmbiguousLayout)
    print("inside the swizzledViewDidLayoutSubviews method for \(Self.self) ")
    swizzledViewDidLayoutSubviews()
  }

  private static let swizzleImplementation: Void = {
    guard let original = class_getInstanceMethod(UIViewController.self, #selector(UIViewController.viewDidLayoutSubviews as (UIViewController) -> () -> Void)),
      let swizzled = class_getInstanceMethod(UIViewController.self, #selector(UIViewController.swizzledViewDidLayoutSubviews)) else {
        return
    }
    method_exchangeImplementations(swizzled, original)
  }()

  static func swizzle() {
    _ = swizzleImplementation
  }
}

class V: UIViewController {}
UIViewController.swizzle()
let v = V()
PlaygroundPage.current.liveView = v