从导航堆栈中删除视图控制器时,如何删除导航栏项目?

时间:2019-06-03 09:26:28

标签: ios swift uinavigationcontroller

一旦用户登录,我将从导航堆栈中删除登录视图控制器。但是,由登录视图控制器添加的导航栏按钮项仍然保留。如何从导航堆栈中完全删除视图控制器?

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从视图中弹出一样,但对当前视图没有任何更改。

screens

1 个答案:

答案 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"
    }
}

enter image description here