我使用此函数更改实际的应用程序根控制器:
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)包含bonusesStack(stackView)和带有didSet的var奖励:
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,superview是nil。我尝试添加if块进行超级视图检查,但由于某些原因它总是执行O_o)
如果我评论/删除此行(不推荐使用,bcs视图仍然在stackView子视图中),代码在完成块中崩溃
答案 0 :(得分:0)
问题出在我的自定义视图中。我重写了绘制方法并以编程方式处理图层。在xib文件中,此视图包含子视图。不知何故(¯\ _(ツ)_ /¯)这个图层和子视图冲突和崩溃应用程序