我有一个UIViewController
,其中的UITableView
嵌入UINavigationController
中,该UITabBarController
开始。显示的导航栏包括后退按钮,我可以通过编程方式从UITabBarController
更改导航项的标题。
但是我无法将UIBarButtonItem
添加到UITabBarController
的子控制器中。既不在情节提要中,也没有编程方式。
我还尝试将子控制器嵌入UINavigationController
中,但这只是添加了第二个导航栏。如何从UIBarButtonItem
的子元素中添加UITabBarController
?
答案 0 :(得分:0)
尝试以下代码以编程方式设置左右BarButton。您可以在viewDidload
的子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)
并添加以下代码以确保导航栏的属性为true。.
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)
}
答案 1 :(得分:0)
我有一个建议给你。请仅移除Show Segue
至Person List ViewController
之间的Person Detail ViewController
。然后您嵌入导航到Person Detail ViewController
。
然后在didselect
tableview方法上,将“ Person Detail ViewController”设置为 RootViewController 。然后,您也可以在子ViewController中添加NavigationBar项。
答案 2 :(得分:0)
在情节提要中,视图控制器位于导航控制器内部。并且您的子视图控制器是视图控制器的INSIDE选项卡栏控制器。您无法添加条形按钮,因为您无法访问navigationController
属性(在子控制器中为零)。
通过访问navigationController
和tabBarController
进行调试。就您而言,它最有可能是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)
}
}