当视图布局不明确时,如何使iOS应用崩溃?

时间:2019-10-22 17:26:18

标签: ios crash autolayout

我想通知团队中的开发人员,并防止他们在创建具有模糊约束的视图时走得更远。为此,我要使手机崩溃(在调试中)。我可以定期轮询以查看层次结构中是否有任何hasAmbiguousLayout设置为true,但这不是很好。但是,iOS似乎在其“运行时问题”区域中报告了不明确的布局。因此,对于模棱两可的布局,必须有UIViewAlertForUnsatisfiableConstraints的等效项。如何使其崩溃?

1 个答案:

答案 0 :(得分:1)

混淆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