我使用此函数更改实际的应用程序根控制器:
class func setRootController(newController: UIViewController, animation: UIViewAnimationOptions? = nil) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
if animation != nil {
let currentController = appDelegate.window!.rootViewController!
UIView.transition(from: currentController.view, to: newController.view, duration: 0.6, options: animation!, completion: { (completed) in
appDelegate.window?.rootViewController = newController
})
} else {
appDelegate.window?.rootViewController = newController
}
}
我的控制器将出现(使用 setRoot 时调用两次:1 - 当控制器创建并开始动画时,2 - 在完成块中):
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
balanceView.bonuses = bonuses
}
我的balanceView(只是一个UIView)包含bonusStack(stackView)和var bonus with didSet:
var bonuses: [Bonus]! {
didSet {
for subview in bonusesStack.arrangedSubviews {
bonusesStack.removeArrangedSubview(subview)
subview.removeFromSuperview()
}
bonuses.forEach { (bonus) in
let bonusView = BonusBalanceView.loadFromXib(bonus: bonus)
bonusesStack.addArrangedSubview(bonusView)
}
}
}
class func loadFromXib(bonus: Bonus) -> BonusBalanceView {
let bonusView = Bundle.main.loadNibNamed(String(describing: BonusBalanceView.self), owner: nil, options: nil)?.first as! BonusBalanceView
// some code here
return bonusView
}
当第二次调用 willAppear 时,代码在第 subview.removeFromSuperview()
行崩溃(第二次调用 bcs,超级视图为零。我尝试添加 if 块以进行超级视图检查,但由于某些原因,它总是执行O_o)
如果我注释/删除此行(不推荐,bcs 视图仍在堆栈视图子视图中),代码在完成块中崩溃
问题出在我的自定义视图中。我覆盖了绘制方法并以编程方式处理图层。在 xib 文件中,此视图包含子视图。不知何故( )̄\_(ツ)_/̄此图层和子视图冲突和崩溃应用程序