我有一个自定义 View Controller ,我在其中创建了一个带有多个按钮的自定义导航栏。我将该自定义 View Controller 用作多个子 Controller 的父级(以在多个 Controller 中使用相同的导航栏)。我正在导航在某些按钮上点击 someController。问题是,每次我单击该按钮时都会创建该 viewcontroller 的实例。当我向后导航时,会出现相同的 Controller 。
这是菜单按钮点击的 Action :
@objc func showMenu(){
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let menuVC = storyBoard.instantiateViewController(withIdentifier: "MenuVC") as! MenuVC
if menuVC.view.window ==nil {
UIView.transition(with: self.view, duration: 0.5, options: .curveEaseIn, animations: {
self.present(menuVC, animated: true, completion: nil)
})
} else {
// view controller is visible
}
}
这是点击后退按钮的 Action :
@objc func backBtnPressed(){
self.dismiss(animated:true,complition:nil)
}
我试过 viewController.view.window 但问题是每次按下按钮时都会创建 baseViewController 的新实例。如何避免创建多个实例?我没有使用导航 Controller 。
如何知道 Controller 已经出现在这个场景中。
最佳答案
创建 var menuVC
变量作为实例变量,而不是局部变量,然后像下面这样检查是否为 nil。
if menuVC != nil {
// use the created instance of menuVC
} else {
// create menuVC
}
这样你只有一个menuVC
实例。如有任何疑问,请发表评论。
关于ios - 避免 View Controller 的多实例创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51593583/