UIApp为零,这意味着我们无法将控制操作分派到其目标

我正在将文件从一个模块更改为另一个模块,这样做是在我的一项测试中开始出现此错误。早些时候,它的工作情况绝对不错。

[Assert] UIApp为零,这意味着我们无法将控制操作调度到其目标。如果这个断言被击中,我们可能在没有执行UIApplicationmain()的情况下到达了这里,这很可能意味着此代码未在应用程序中运行(也许单元测试在没有主机应用程序的情况下运行),并且将无法按预期工作。

在代码中添加viewDidLoad()中的按钮

    private lazy var button: ABCTypeButton = {
        let button = ABCTypeButton(title: viewModel.title,buttonType: .Payment).withAutoLayout()
        button.accessibilityLabel = viewModel.title
        button.accessibilityIdentifier = "paymentButton"
        button.resetTintColor()
        button.addTarget(self,action: #selector(ABCViewController.action1),for: .touchUpInside)
        button.addTarget(self,action: #selector(ABCViewController.action2),for: .touchDown)
        button.addTarget(self,action: #selector(ABCViewController.action3),for: [.touchUpOutside,.touchDragExit])
        return button
    }()

@objc private func action1() {
// code
}

public class ABCTypeButton: UIControl {

let iconImageView = UIImageView()
let buttonTitleLabel = UILabel()
private let chevronImageView = UIImageView(image: Icon.navigateNext.image)
private let stackView = UIStackView().withAutoLayout()

public init(title buttonTitle: String,buttonType: FeeButtonType,height: CGFloat = Spacing.four) {
    super.init(frame: CGRect.zero)
    setupViews(buttonTitle,buttonType: buttonType)
    setupConstraints(height: height)
} 
}

尝试从测试中点击按钮。

    func test() {
    let viewController = ViewController(viewModel: viewModel)
    let button = viewController.view.findViewByIdentifier("paymentButton") as! ABCTypeButton
    // I Checked that button is not nil
    button.sendactions(for: .touchUpInside)
    XCTAssertEqual(viewController.value,button.accessibilityIdentifier)
}

未调用目标方法action1()

xuelei4460 回答:UIApp为零,这意味着我们无法将控制操作分派到其目标

我只是遇到了这个问题,并为touchUpInside事件做了一个粗略的扩展。显然可以重构为接受您想调用的任何事件。

extension UIButton {
  public func touchUpInside(forTarget target: UIViewController) {
    guard let action = actions(forTarget: target,forControlEvent: .touchUpInside)?.first else {
      assertionFailure("could not find touchUpInside action for target")
      return
    }

    target.perform(Selector(action))
  }
}
本文链接:https://www.f2er.com/3160588.html

大家都在问