一旦用户登录,我将从导航堆栈中删除登录视图控制器。但是,由登录视图控制器添加的导航栏按钮项仍然保留。如何从导航堆栈中完全删除视图控制器?
static func removePreviousFromNavigationStack(_ navVC: UINavigationController) {
var navArr = navVC.viewControllers
for elem in navArr {
if elem.isKind(of: LoginViewController.self) {
if let vc = StateData.loginVC {
vc.navigationItem.leftBarButtonItem = nil // is not working as intended
vc.navigationItem.rightBarButtonItem = nil
vc.navigationItem.title = "Foo"
}
//elem.removeFromParent()
}
}
navArr.remove(at: navArr.count - 2)
navVC.viewControllers = navArr
}
Flow: HomeVC -> ApplyVC -> LoginVC -> FormVC
登录FormVC
后,我调用remove方法从堆栈中删除LoginVC
。这将删除VC,但仍保留导航按钮。如果我将导航按钮设置为nil,则ApplyVC
的leftButtonItem,后退按钮,右键按钮,主页按钮不会显示。有一个透明的后退按钮,当单击该按钮时,将显示ApplyVC
的导航栏按钮,就好像LoginVC
从视图中弹出一样,但对当前视图没有任何更改。
答案 0 :(得分:2)
尝试在推LoginVC
时而不是在FormVC
可见后移除FormVC
。
我创建了与您相同的NavigationStack
。
1。。在rightBarButton
HomeVC
class HomeVC: UIViewController {
var rightBarItem: UIBarButtonItem = {
return UIBarButtonItem(barButtonSystemItem: .bookmarks, target: nil, action: nil)
}()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "HomeVC"
self.navigationItem.rightBarButtonItem = rightBarItem
}
}
class ApplyVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.title = "ApplyVC"
}
}
2。。在rightBarItem
LoginVC
class LoginVC: UIViewController {
var rightBarItem: UIBarButtonItem = {
return UIBarButtonItem(barButtonSystemItem: .add, target: nil, action: nil)
}()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "LoginVC"
self.navigationItem.rightBarButtonItem = rightBarItem
}
@IBAction func onTapButton(_ sender: UIButton) {
var controllers = self.navigationController?.viewControllers
let formVC = self.storyboard?.instantiateViewController(withIdentifier: "FormVC") as! FormVC
controllers?.removeAll(where: { $0 is LoginVC })
controllers?.append(formVC)
if let controllers = controllers {
self.navigationController?.setViewControllers(controllers, animated: true)
}
}
}
在上面的代码中,我过滤了LoginVC
,并从FormVC
navigationController’s
中添加了viewControllers array
。
class FormVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.title = "FormVC"
}
}