How to add button item to existing navigation bar programmatically Xcode - ios

I have recently been working on making my application programmatically and I have run into an error, where the tab bar controller is producing a navigation controller as well (which I want for every page), however I am struggling to find a way to add a button onto the bar, like a done button in the top right, from the ViewController itself - not the tab bar controller.
Basically I am trying to add a submit button which will perform an action as declared in the ViewController, however the only way I have found is to either make the navigation controller individually in each View controller which would be less efficient or to add the button in the Tab Bar controller, but that would mean copying the function (which is specific to other items on the View controller page) into the tab bar controller which would be a nightmare.
This is the code on the Controller - newReportScreen in the viewDidLoad function
//setting the nav bar submit button
let navBar = UINavigationBar()
view.addSubview(navBar)
let submitItem = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(SubmitButtonTouched))
let navItem = UINavigationItem(title: "Submit")
navItem.rightBarButtonItem = submitItem
navBar.setItems([navItem], animated: false)
which is conflicting with the code in the TabBar controller
//setting up the variable for the first view controller which will be used for the tab bar
let firstViewController = MapVC()
//set the nav title
firstViewController.title = "Home"
//initialising the first tab bar item, which will have the title of Home, the image named below and the tag number, showing the position on the bar
firstViewController.tabBarItem = UITabBarItem(title: "Home", image: UIImage(named: "Home.png"), tag: 0)
//initialising the second of the view controllers which will be used to access from the tab bar controller
let secondViewController = localReportsTVC()
//set the nav title
secondViewController.title = "Local Reports"
//setting the second view controller on the tab bar and giving it a title, image and location on the bar
secondViewController.tabBarItem = UITabBarItem(title: "Local Reports", image: UIImage(named: "Local.png"), tag: 1)
//setting up the third view controller to be referenced on the tab bar controller
let thirdVC = NewReportScreen()
//set the nav title
thirdVC.title = "New Report"
//setting the third view conteroller to be on the tab bar with the image, name and the location on the bar in relation to the other items
thirdVC.tabBarItem = UITabBarItem(title: "New Report", image: UIImage(named: "Plus Icon.png"), tag: 2)
//setting up the third view controller to be referenced in the tab bar controller
let fourthVC = MyReportsTVC()
//set the nav title
fourthVC.title = "My Reports"
//setting the third item on the tab bar up so that it has a position, image and title
fourthVC.tabBarItem = UITabBarItem(title: "My Reports", image: UIImage(named: "MyReports.png"), tag: 3)
//setting up the fifth section of the tab bar, where it will be referenced later
let fithVC = SettingsScreen()
//set the nav title
fithVC.title = "Settings"
//setting up the fifth item, so that it has a title, image and position on the bar
fithVC.tabBarItem = UITabBarItem(title: "Settings", image: UIImage(named: "Settings Icon.png"), tag: 4)
//initialising the final tab bar wih all of the elements from above
let tabBarList = [firstViewController, secondViewController, thirdVC, fourthVC, fithVC]
//setting the view controllers equal to the tab bar list defined above - also adding in the navigation controller to each of the tabs so that they have a title and also a navigation controller to add the back button in
viewControllers = tabBarList.map { UINavigationController(rootViewController: $0)}
I may be overthinking this, but I have struggled to work around this, so any help is greatly appreciated!

When creating your UITabBar you're already adding UINavigationController's.
viewControllers = tabBarList.map { UINavigationController(rootViewController: $0)}
This is correct.
Then in each View Controller, you can set its navigation bar items via UIViewControllers navigationItem property:
//setting the nav bar submit button
let submitItem = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(SubmitButtonTouched))
self.navigationItem.rightBarButtonItem = submitItem
doing this in viewDidLoad is correct.

Related

UITabBar selected tab doesn't change tint color on launch

I have subclassed UITabBarController to allow for some customization specific to my app. It is the root view controller of my UIWindow and displays itself correctly on launch, and even shows the correct tab's view hierarchy as well.
The problem is with the selected tabbar item's tint color. Inside viewDidLoad of the custom tab bar controller subclass, I have set both the unselected and selected tint colors for the tab bar. See below:
override func viewDidLoad() {
super.viewDidLoad()
tabBar.tintColor = .tabBarItemActiveTint
tabBar.unselectedItemTintColor = .tabBarItemInactiveTint
tabBar.barTintColor = .tabBarBg
let dashboardVC = DashboardViewController.build()
let settingsVC = SettingsTableViewController.build()
let settingsNavC = UINavigationController(rootViewController: settingsVC)
settingsNavC.navigationBar.barStyle = .black
viewControllers = [dashboardVC, settingsNavC]
selectedViewController = dashboardVC
// Accessing the view property of each tab's root view controller forces
// the system to run "viewDidLoad" which will configure the tab icon and
// title in the tab bar.
let _ = dashboardVC.view
let _ = settingsVC.view
}
As you can see, the controller has its child view hierarchies set, and the views are loaded at the bottom so their respective viewDidLoad methods run where I have code that sets the tabBarItem. Here's an example from the dashboard view controller:
tabBarItem = UITabBarItem(title: "Dashboard", image: UIImage(named: Theme.dashboardTabBarIcon), tag: 0)
Everything about this works except for the selected icon and title. When the app launches I can see the tab bar, the first view hierarchy (the dashboard) is visible onscreen and the tabs all function properly. But the dashboard's icon and title are in an unselected state. I have to actually tap the tab bar icon to get the state to change such that it is selected.
Once you tap one of the tabs, the selected state works as normal. The issue is only on the first presentation of the tab bar.
Here is an image showing the initial state of the tab bar on launch. Notice the dashboard icon is not selected, even though it is the presented view controller.
UPDATE
Skaal's answer below solved the problem for me.
For future reference: the key difference between the code presented here in my question and his sample in the answer is that the tabBarItem is set in viewDidLoad of his custom TabBarController class. By contrast, that code was placed within the viewDidLoad method of each constituent view controller class in my project. There must be a timing issue of when things are called that causes the tint color to not be set in one scenario and work properly in the other.
Key Takeaway: If you set up a tab bar controller programmatically, be sure to set your tabBarItem properties early on to ensure tint colors work properly.
You can use :
selectedIndex = 0 // the index of your dashboardVC
instead of selectedViewController
EDIT - Here is a working sample of UITabBarController:
class TabBarController: UITabBarController {
private lazy var firstController: UIViewController = {
let controller = UIViewController()
controller.title = "First"
controller.view.backgroundColor = .lightGray
return controller
}()
private lazy var secondController: UIViewController = {
let controller = UIViewController()
controller.title = "Second"
controller.view.backgroundColor = .darkGray
return controller
}()
private var controllers: [UIViewController] {
return [firstController, secondController]
}
override func viewDidLoad() {
super.viewDidLoad()
tabBar.tintColor = .magenta
tabBar.unselectedItemTintColor = .white
tabBar.barTintColor = .black
firstController.tabBarItem = UITabBarItem(title: "First", image: UIImage(), tag: 0) // replace with your image
secondController.tabBarItem = UITabBarItem(title: "Second", image: UIImage(), tag: 1) // replace with your image
viewControllers = controllers
selectedViewController = firstController
}
}

UITabBarItem's title does not shown when using with Navigation controller

I'm having a trouble with my very simple app.
My app simply have 2 mains UIViewControllers called News and Category, each of them has their own UINavigationController.
So in AppDelegate.swift, I've done like this
window = UIWindow(frame: UIScreen.main.bounds)
let tabBarController = UITabBarController()
let newsVC = NewsVC()
// CREATE TAB BAR ITEM WITH TITLE ONLY
let newsVCTabBarItem = UITabBarItem(title: "News", image: nil, tag: 1)
newsVC.tabBarItem = newsVCTabBarItem
let categoryVC = CategoryVC()
// CREATE TAB BAR ITEM WITH TITLE ONLY
let categoryVCTabBarItem = UITabBarItem(title: "Category", image: nil, tag: 2)
categoryVC.tabBarItem = categoryVCTabBarItem
let rootViewControllers = [newsVC, categoryVC]
// CREATE NAVIGATION CONTROLLER FOR EACH OF THEM
tabBarController.viewControllers = rootViewControllers.map {
UINavigationController(rootViewController: $0)
}
window?.rootViewController = tabBarController
window?.makeKeyAndVisible()
When I run this simple application, the tab bar items do not show anything :(
But when I change the UITabBarItem to system's styles like this
let newsVCTabBarItem = UITabBarItem(tabBarSystemItem: .featured, tag: 1)
It's working perfectly! So hard to understand!
So does anyone know why my title-only tab bar item does not working? Have I missed something important?
Thanks in advance!
Add title property to the ViewControllers to show the title in UITabBarItem.
var title: String? { get set }
Set the title to a human-readable string that describes the view. If
the view controller has a valid navigation item or tab-bar item,
assigning a value to this property updates the title text of those
objects.
let newsVC = ViewController()
newsVC.title = "News"
.....
let categoryVC = ViewController2()
categoryVC.title = "Category"
.....
Or
Assign an image to the UITabBarItem to see the result.
let newsVCTabBarItem = UITabBarItem(title: "News", image: UIImage(named: "news.png"), tag: 1)
....
let categoryVCTabBarItem = UITabBarItem(title: "Category", image: UIImage(named: "category.png"), tag: 2)
.....
Update:
Tab bar items are configured through their corresponding view
controller. To associate a tab bar item with a view controller, create
a new instance of the UITabBarItem class, configure it appropriately
for the view controller, and assign it to the view controller’s
tabBarItem property. If you don't provide a custom tab bar item for
your view controller, the view controller creates a default item
containing no image and the text from the view controller’s title
property.

How to navigate one to another navigation controller iOS

My scenario I have three view controller A, B and C. A is the root view controller, In A button click to navigate B view controller and In side B view controller button click to navigate C view controller. It is working fine by below code.
let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "firstview") as? ViewController
self.navigationController?.pushViewController(vc!, animated: true)
But, Each view controller I want to show separate navigation bar or navigation controller. If i set bar it is not covering status bar but if I embed navigation controller it showing proper bar in story board but output showing previous view controller bar and back button. Here, problem is A view controller I made transparent but B and C also showing transparent. I want to show separate navigation bar in B and C.
enter image description here
it seems you have embedded navigation controller on root view controller and when you move from one Vc to another the navigation bar is the same as root view controller with a back button and it is obvious because you have embedded the navigation controller in root view controller.
one thing you can do is instead of making a segue like this:
self.navigationController?.pushViewController(vc!, animated: true)
you can try;
self.present(vc, animated: true, completion: nil)
this code present your view controller B and C without the navigation controller
You will need to modify/update the title of the navigation bar using
self.navigationItem.title = "your_title"
If you want to add some fancy view to the navigation bar you can use this
func updateTitle(_ title: String?) {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 44, height: 400))
label.text = title
label.backgroundColor = .clear
label.textColor = .white
self.navigationItem.title = ""
self.navigationItem.titleView = label
}
Hope this helps

Custom Navigation Items Not Being Displayed on Top Level View Controller

I have a project where I have TableViewCells push to different View Controllers. In this project, I use custom navigation controllers. This is the code of the navigation controller in the first view controller:
//Design of Header
let nav_background = UIImage(named: "header_background")
navigationController?.navigationBar.setBackgroundImage(nav_background, for: .default)
navigationController?.navigationBar.layer.shadowOffset = CGSize(width: 0, height: 1)
navigationController?.navigationBar.layer.shadowOpacity = 0.16
navigationController?.navigationBar.layer.shadowRadius = 10
let account = UIImage(named: "header_account")
let imageView = UIImageView(image: account)
let blankView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.layer.shadowOffset = CGSize(width: -3, height: 3)
imageView.layer.shadowOpacity = 0.16
imageView.layer.shadowRadius = 10
self.navigationController?.navigationBar.topItem?.rightBarButtonItem?.customView = imageView
self.navigationController?.navigationBar.topItem?.leftBarButtonItem?.customView = blankView
The first view controller only displays the custom background and no other properties.
This is the code of the second view controller which is loaded when a cell in the TableView is selected:
//Design of Header
let account = UIImage(named: "header_account")
let accountView = UIImageView(image: account)
let back = UIImage(named: "header_backarrow")
let backView = UIImageView(image: back)
navigationItem.leftBarButtonItem?.customView = backView
navigationItem.rightBarButtonItem?.customView = accountView
Theoretically, everything should be replaced with the code written here and the titles listed in the View Controller's properties(This works for all view controllers except the first one.) I am taking all this directly off of the Apple webpage: https://developer.apple.com/documentation/uikit/uinavigationcontroller
Here are the exact paragraphs I am referencing:
Left Item:
If the new top-level view controller has a custom left bar button item, that item is displayed. To specify a custom left bar button item, set the leftBarButtonItem property of the view controller’s navigation item.
Middle Item:
If no custom title view is set, the navigation bar displays a label containing the view controller’s default title. The string for this label is usually obtained from the title property of the view controller itself. If you want to display a different title than the one associated with the view controller, set the title property of the view controller’s navigation item instead.
Right Item:
If the new top-level view controller has a custom right bar button item, that item is displayed. To specify a custom right bar button item, set the rightBarButtonItem property of the view controller’s navigation item.
Does anybody know how to fix this? Thanks.
Your code doesn't work because customView is nil in most cases.
If you want to set a navigation item to a UIImage, create a new UIBarButtonItem from the image, and then assign the bar button item.
For example, from a UIImage:
let accountItem = UIBarButtonItem(image: account, style: .plain, target: nil, action: nil)
self.navigationController?.navigationBar.topItem?.rightBarButtonItem = accountItem
To create one from a custom view, use:
let accountItem = UIBarButtonItem(image: imageView)
self.navigationController?.navigationBar.topItem?.rightBarButtonItem = accountItem
Please note that this can still fail if navigationController is nil or if topItem is nil.

Navigation bar is hiding on swipe and scroll

I am customising navigation bar this way in swift
navigationItem.title = "SUPPORT"
let menuButton = UIBarButtonItem(image: UIImage(named: "menuIcon"), style: UIBarButtonItemStyle.Plain, target: self, action: "showMenu:")
navigationItem.rightBarButtonItem = menuButton
self.navigationItem.setHidesBackButton(true, animated:false)
I am customising navigation item in all view controller and table view controller. My problem is navigation is hiding when I swipe in any view controller or scroll in table view controller. How to fix navigation bar being hidden on swipe and scroll means it should not be hidden everytime.
add this to your root view controller ( of navigation controller )
self.navigationController?.hidesBarsOnSwipe = false

Resources