将 UIBarButtomItem 添加为 UITabBarController 的 Child

Add UIBarButtomItem as Child of UITabBarController

我有一个 UIViewControllerUITableView 嵌入 UINavigationController,开始 UITabBarController。显示的导航栏包括后退按钮,我可以从 UITabBarController.

以编程方式更改导航项的标题

但是我无法将 UIBarButtonItem 添加到 UITabBarController 的 child 控制器。既不在故事板中,也不以编程方式。

我还尝试将 child 控制器嵌入到 UINavigationController 中,但这只是添加了第二个导航栏。如何从 UITabBarController 的 child 添加 UIBarButtonItems?

尝试使用以下代码设置左右 BarButton programatically.You 可以在 viewDidload 您的 child TabBarController 中添加给定的代码。

 let cancelBtn =  UIButton(type: .custom)
 cancelBtn.frame = CGRect(x: 0, y: 0, width: 40, height: 15)
 cancelBtn.setTitle("Cancel", for: .normal)
 cancelBtn.setTitleColor(UIColor.init(red: 240/255, green: 36/255, blue: 70/255, alpha: 1.0), for: .normal)
 cancelBtn.addTarget(self, action: #selector(cancelTapped), for: .touchUpInside)
 self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: cancelBtn)

 let resetBtn =  UIButton(type: .custom)
 resetBtn.setTitle("Reset", for: .normal)
 resetBtn.setTitleColor(UIColor.init(red: 240/255, green: 36/255, blue: 70/255, alpha: 1.0), for: .normal)
 resetBtn.addTarget(self, action: #selector(resetTapped), for: .touchUpInside)
 self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: resetBtn)

并添加以下代码以确保导航栏的 属性 为真..

override func viewWillAppear(_ animated: Bool)
    {
        super.viewWillAppear(animated)

        // Hide the navigation bar on the this view controller
        self.navigationController?.setNavigationBarHidden(true, animated: animated)
    }

    override func viewWillDisappear(_ animated: Bool)
    {
        super.viewWillDisappear(animated)

        // Show the navigation bar on other view controllers
        self.navigationController?.setNavigationBarHidden(false, animated: animated)
    }

我有一个建议给你。请只删除 Person List ViewControllerPerson Detail ViewController 之间的 Show Segue。然后你嵌入导航到Person Detail ViewController

然后在 didselect tableview 方法中将“Person Detail ViewController”设置为 RootViewController 然后您可以添加 NavigationBar Item在孩子ViewController也。

在您的故事板中,您的视图控制器位于导航控制器内。而您的子视图控制器是您的视图控制器的 INSIDE 选项卡栏控制器。您无法添加栏按钮,因为您无法访问 navigationController 属性(在您的子控制器案例中为 nil。)

通过访问 navigationControllertabBarController 对其进行调试。在你的情况下,它应该是 tabBarController?.navigationController 最有可能。

编辑

这是我在代码中维护导航栏的方式:

final class MyVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavigationBar(withTitle: "MyVC")
    }
}
extension UIViewController {
    func setupNavigationBar(withTitle title: String? = nil) {
        let backButton = UIBarButtonItem(image: #imageLiteral(resourceName: back), style: .plain, target: self, action: #selector(popVC(animated:)))
        backButton.tintColor = .white
        navigationItem.leftBarButtonItem = backButton
        navigationItem.title = title
    }

    @objc
    func popVC(animated: Bool = true) {
        navigationController?.popViewController(animated: true)
    }
}