Custom Navigation Items Not Being Displayed on Top Level View Controller - ios

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.

Related

How to add button item to existing navigation bar programmatically Xcode

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.

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
}
}

SWIFT: Pass image from First View Controller to Second View Controller on button click

im a Swift Beginner and I really need your help. Im working on my first IOS App. I'm working with multiple ViewControllers now and I want a User to fill out some information like Name, Date and to choose an image from his Gallery. After that, I want that he clicks on a button and the image has to be displayed in another ViewController. So my question now is, how can I create a new ImageView in my SecondViewController by clicking on this button in my FirstViewController.
This is the code I have used for creating an ImageView in the same ViewController, but now I need help to create an ImageView in another ViewController:
`let imageName = "barcelona-allgemeine-informationen-at"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)
imageView.translatesAutoresizingMaskIntoConstraints = false
var imageCons:[NSLayoutConstraint] = []
view.addSubview(imageView)`
Follow below steps:-
Create ImageView in Second view controller using Storyboard or Programatically.
Take UIImage variable in Second View controller.
var image: UIImage?
Pass captured image on First View controller by camera/Gallery to second view controller like this
let viewController = SecondViewController(nibName:"SecondViewController", bundle: nil)
viewController.image = pickedImage
navigationController?.pushViewController(viewController, animated: true)
In Second View Controller assign this image to your imageview
imageView.image = image

NavigationItem's titleView not animating correctly

I have looked at all the similar questions I could find and I have not found a solution to this problem.
I am setting the titleView property like this in viewDidLoad:
self.navigationItem.titleView = label
The view controller is part of a navigation stack. When you tap on a row in in the previous view controller it pushes this controller onto the stack. Completely normal UINavigationController stuff.
As this view controller begins to animate in, the label appears at the origin (top left) and then stays there until the view controller finishes animating and then it jumps (no animation) to the proper position in the middle of the nav bar.
After tapping on the back button the title view animates out correctly, just like a normal title would.
Here is the code in viewDidLoad:
let label = UILabel(frame: CGRect.zero)
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = .red
label.text = "test"
label.sizeToFit()
self.navigationItem.titleView = label
Things I've tried:
Specify a frame: no change. Plus I don't want to specify a frame. I don't want to make assumptions about the height of the nav bar.
Moved it to viewWillAppear: no change.
Moved it to viewDidAppear: better but still not right. The label does not appear at all until the animation is complete and then it appears where it should, no animation it just appears. The correct behaviour is to animate in from right to left like a normal title would.
This is easily reproducible with the Master-Detail project template in Xcode. If you want to try it just add the code above to the top of configureView() in DetailViewController.swift. In that template the navigation item's title is hardcoded into the storyboard. You can easily remove it by searching for "Detail". Click the result that says Navigation Item: Title = "Detail" and then remove the string from the Inspector pane.
Update
#synndicate's suggestion does work perfectly for the UILabel example above. But my real problem is with a UIStackView. When I use a stack view following the approach #synndicate suggests I get yet another animation problem. This time the title view starts sliding in but animates all the way to the origin. When the animation is finished it snaps to where it should be.
Here's the code in prepare(for:sender:) as #synndicate suggests...
let label = UILabel(frame: CGRect.zero)
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = .red
label.text = "test"
let stackView = UIStackView(frame: CGRect.zero)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.addArrangedSubview(label)
stackView.sizeToFit()
controller.navigationItem.titleView = stackView
Any further suggestions?
Also, this is Xcode 8 and iOS 10.
Update 2
I have discovered that the stack view code above animates perfectly (just like an ordinary title would) in viewDidLoad for a view controller where the root of the nav hierarchy is a UINavigationController. The problem occurs when the root of the nav hierarchy is a UISplitViewController.
So I guess I could update my question to this...
How do I configure a UIStackView that will be set on the navigationItem's titleView property where the root of the navigation hierarchy is a UISplitViewController?
Are you able to move the code to before you push the view controller on the stack?
e.g. In MasterViewController.swift of the Master-Detail project
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = tableView.indexPathForSelectedRow {
let object = objects[indexPath.row] as! NSDate
let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
let label = UILabel()
label.textAlignment = .center
label.backgroundColor = .red
label.text = "test"
label.sizeToFit()
controller.navigationItem.titleView = label
}
}
}
If you want the stackView to appear on a specific view controller of the navigation stack, simply add it in the view controller
self.view.addSubview(stackView)

Navigation bar in appended view controllers

I currently have three view controllers appended to one single view controller called V1. V1 has a horizontal scrollview which can push the other three views on the screen when scrolled.
I would like to embed a Navigation Bar in each of the three view controllers so that each one can have its own independent bar buttons and titles based on which page is scrolled to.
My problem is determining where I embed the navigation bar. I tried V1 but it is not giving the results I would like. How can I make each view have its own navigation bar?
class ViewController: UIViewController {
#IBOutlet var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
//Changes Navi bar
// navigationController!.navigationBar.barTintColor = UIColor(red: 237/255, green: 15/255, blue: 140/255, alpha: 1)
// navigationController!.navigationBar.barStyle = UIBarStyle.Black
// Do any additional setup after loading the view, typically from a nib.
let v1 = storyboard!.instantiateViewControllerWithIdentifier("A") as! Offers
let v2 : View2 = View2(nibName: "View2", bundle: nil)
let v3 = storyboard!.instantiateViewControllerWithIdentifier("C") as! DiscoveryPage
self.addChildViewController(v1)
self.scrollView.addSubview(v1.view)
v1.didMoveToParentViewController(self)
self.addChildViewController(v2)
self.scrollView.addSubview(v2.view)
v2.didMoveToParentViewController(self)
self.addChildViewController(v3)
self.scrollView.addSubview(v3.view)
v3.didMoveToParentViewController(self)
//Set the frame
var v2Frame : CGRect = v2.view.frame
v2Frame.origin.x = self.view.frame.width
v2.view.frame = v2Frame
var v3Frame : CGRect = v3.view.frame
v3Frame.origin.x = self.view.frame.width * 2
v3.view.frame = v3Frame
self.scrollView.contentSize = CGSizeMake(self.view.frame.width * 3, self.view.frame.height)
}
}
A little explanation here, hope it'll answer your question.
If you're using a UINavigationController to manage your flow of view controllers. Then you don't need to provide custom navigation bar for every view controller, the top left and right bar button item and title of the view controller are part of UINavigationItem and UINavigationItem is a property of UIViewController.
Every time you push a view controller onto a UINavigationController, the navigation controller takes the navigation item from view controller and setup its item onto the navigation bar. The navigation bar is managed by UINavigationController automatically.
You just need to edit and provide your navigation related info in the associated UINavigationItem.
In the storyboard, if you don't see a navigation item associated to a view controller, you can drag an item from objects and drop it inside view controller:
If you click on a navigation item, you can edit these three option from property inspector:
If you drag a UIBarButtonItem from objects to your UINavigationItem associated to your UIViewController, it'll automatically add it to your left bar button.

Resources