Swift: Hidden navigation bar appears when tap occurs in view - ios

Introduction
I'm creating a simple app in with the RootViewController is embedded in a UINavigationController. I have a UIView subclass "landscapeView" with a UICollectionView in it that fills the view. "landscapeView" is hidden in portrait and displayed in landscape device orientation.
Issue
When the device is rotated to a landscape orientation I hide the navigationBar and the portrait table view "rootTableView", while showing the "landscapeView". However, the navigationBar appears when I tap the screen in landscape orientation. I can't figure out how to disable this tap to show thing. (I have `navigationController?.hidesBarsOnTap = false, its setup to default in storyboard).
Clarification: hiding the navigation bar works perfectly depending on device orientation.
Question
How can I prevent the navigationBar from appearing when the screen is tapped in landscape orientation?
Code
viewWillTransition() in the "RootViewController"
private let landscapeView = LandscapeView(frame: .zero)
private let rootTableView = UITableView(frame: .zero, style: .grouped)
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
var isLandscape = true
switch UIDevice.current.orientation {
case .landscapeLeft:
navigationController?.navigationItem.searchController?.accessibilityElementsHidden = true
isLandscape = true
case .landscapeRight:
navigationController?.navigationItem.searchController?.accessibilityElementsHidden = true
isLandscape = true
case .portrait, .portraitUpsideDown, .faceUp, .faceDown, .unknown:
isLandscape = false
navigationController?.navigationItem.searchController?.accessibilityElementsHidden = false
default:
break
}
if isLandscape {
navigationController?.setNavigationBarHidden(true, animated: false)
self.landscapeView.isHidden = false
// This simply tells the "landscapeView" to layoutSubviews() and reloadData() for the collectionView within.
landscapeViewDelegate?.landscapeViewWillAppear(inDarkMode: inDarkMode)
}
UIView.animate(withDuration: 0.6, delay: 0, options: .layoutSubviews, animations: {
// This is a tableView displayed in portrait mode.
self.rootTableView.alpha = isLandscape ? 0 : 1
self.landscapeView.alpha = isLandscape ? 1 : 0
}) { (success) in
if isLandscape == false {
self.landscapeView.isHidden = true
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
return
}
}
Thanks for reading.

The issue is that you checked Hide Bars When Vertically Compact for your navigation controller in the storyboard. This property brings that tap behaviour with it:
When the value of this property is true, the navigation controller
hides its navigation bar and toolbar when it transitions to a
vertically compact environment. Upon returning to a vertically regular
environment, the navigation controller automatically shows both bars
again. In addition, unhandled taps in the content area cause the
navigation controller to show both bars again. The default value of
this property is false.
You can uncheck that property since you take care of showing and hiding the navigation bar in the viewWillTransition method yourself.

Related

UIViewController autorotation manual layout

I have a view Controller VC1 which can autorotate to all orientations. I set the interface manually by activating and deactivating appropriate autolayout constraints. On autorotation, I do:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
let orientation = UIApplication.shared.statusBarOrientation
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { [unowned self] (_) in
let orient = UIApplication.shared.statusBarOrientation
self.layoutInterfaceForOrientation(orient)
}, completion: { [unowned self] (UIViewControllerTransitionCoordinatorContext) -> Void in
let orient = UIApplication.shared.statusBarOrientation
NSLog("rotation completed to \(orient.rawValue)")
self.layoutInterfaceForOrientation(orient)
})
}
Now comes the problem. I have VC2 which is invoked via a segue from VC1 by a touch of a button. VC2 supports only landscape mode. So if my VC1 is in portrait mode and the segue gets triggers, VC1 screen is still in portrait mode but starts laying out elements as if the screen is in landscape mode and all my UI looks messed up & garbled while segue is in transition. This is because UIApplication.shared.statusBarOrientation returns landscape mode as the segue is in transition but iPhone is still held vertical.
I tried many things, such as having a flag for segue in progress and disabling autorotation when the flag is set, but no effect. Any ideas?

iOS - Navigation bar does not show large titles when orientation changed

I have largeTitle on my navigation bar which shows correctly.
WHen I change my device orientation to landscape and back to portrait, it becomes regular instead of largeTitle.
This is a tab bar controller. When I switch tabs (to Calendar as in below gif)then the view reloads and shows it correctly
In my tab bar controller I have added this but isn't helping me to readjust largeTitle in navigation bar
override func viewWillTransition(to size: CGSize, with coordinator:
UIViewControllerTransitionCoordinator) {
if UIDevice.current.orientation.isLandscape {
//do something
} else {
self.navigationController?.navigationBar.prefersLargeTitles = true
self.navigationItem.largeTitleDisplayMode = .always
}
}
If i add above code in my tabviewcontroller it doesn't even call. It calls from my tabbar controller but itsn't updating titles to large
I'm struck here. Please let me know how i can fix this
Thanks
You can reset your navigation bar height to default one on changing device orientation (here I reset the whole navigation bar frame for simplicity):
class ViewController: UIViewController {
lazy var navigationControllerLargeTitleFrame: CGRect = {
let navigationController = UINavigationController()
navigationController.navigationBar.prefersLargeTitles = true
return navigationController.navigationBar.frame
}()
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(orientationDidChangeNotification), name: UIDevice.orientationDidChangeNotification, object: nil)
}
#objc func orientationDidChangeNotification(_ notification: NSNotification) {
if UIDevice.current.orientation == .portrait {
navigationController?.navigationBar.frame = navigationControllerLargeTitleFrame
}
}
}

Programatically show the slide over master view in a UISplitViewController

When using a UISplitViewController in portrait mode on an iPad I am given a fullscreen view of my detail view controller which is intended. I can slide from the left and reveal the master view slide over, how can I trigger this slide over programmatically?
There's no easy way to do this it seems, but I have found that using the following code has the intended behaviour:
UIView.animate(withDuration: 0.2, animations: {
self.splitViewController?.preferredDisplayMode = .primaryOverlay
})
Make sure you set the display mode back to automatic on landscape rotation so that it will always show the master and detail like default:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { _ in
if UIDevice.current.orientation == .landscapeLeft || UIDevice.current.orientation == .landscapeRight {
self.splitViewController?.preferredDisplayMode = .automatic
}
}, completion: nil)
}

UIViewController In-Call Status Bar Issue

Issue:
Modally presented view controller does not move back up after in-call status bar disappears, leaving 20px empty/transparent space at the top.
Normal : No Issues
In-Call : No Issues
After In-Call Disappears:
Leaves a 20px high empty/transparent space at top revealing orange view below. However the status bar is still present over the transparent area. Navigation Bar also leaves space for status bar, its' just 20px too low in placement.
iOS 10 based
Modally presented view controller
Custom Modal Presentation
Main View Controller behind is orange
Not using Autolayout
When rotated to Landscape, 20px In-Call Bar leaves and still leaves 20px gap.
I opt-out showing status bar in landscape orientations. (ie most stock apps)
I tried listening to App Delegates:
willChangeStatusBarFrame
didChangeStatusBarFrame
Also View Controller Based Notifications:
UIApplicationWillChangeStatusBarFrame
UIApplicationDidChangeStatusBarFrame
When I log the frame of presented view for all four above methods, the frame is always at (y: 0) origin.
Update
View Controller Custom Modal Presentation
let storyboard = UIStoryboard(name: "StoryBoard1", bundle: nil)
self.modalVC = storyboard.instantiateViewController(withIdentifier: "My Modal View Controller") as? MyModalViewController
self.modalVC!.transitioningDelegate = self
self.modalVC.modalPresentationStyle = .custom
self.modalVC.modalPresentationCapturesStatusBarAppearance = true;
self.present(self.modalVC!, animated: true, completion: nil)
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
toViewController!.view.transform = CGAffineTransform(scaleX: 0.001, y: 0.001)
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.0, options: [.curveEaseOut], animations: { () -> Void in
toViewController!.view.transform = CGAffineTransform.identity
}, completion: { (completed) -> Void in
transitionContext.completeTransition(completed)
})
}
I've been looking for a solution for 3 days. I don't like this solution but didn't found better way how to fix it.
I'he got situation when rootViewController view has bigger height for 20 points than window, when I've got notification about status bar height updates I manually setup correct value.
Add method to the AppDelegate.swift
func application(_ application: UIApplication, didChangeStatusBarFrame oldStatusBarFrame: CGRect) {
if let window = application.keyWindow {
window.rootViewController?.view.frame = window.frame
}
}
After that it works as expected (even after orientation changes).
Hope it will help someone, because I spent too much time on this.
P.S. It blinks a little bit, but works.
I faced this problem too but after I put this method, problem is gone.
iOS has its default method willChangeStatusBarFrame for handling status bar. Please put this method and check it .
func application(_ application: UIApplication, willChangeStatusBarFrame newStatusBarFrame: CGRect) {
UIView.animate(withDuration: 0.35, animations: {() -> Void in
let windowFrame: CGRect? = ((window?.rootViewController? as? UITabBarController)?.viewControllers[0] as? UINavigationController)?.view?.frame
if newStatusBarFrame.size.height > 20 {
windowFrame?.origin?.y = newStatusBarFrame.size.height - 20
// old status bar frame is 20
}
else {
windowFrame?.origin?.y = 0.0
}
((window?.rootViewController? as? UITabBarController)?.viewControllers[0] as? UINavigationController)?.view?.frame = windowFrame
})
}
Hope this thing will help you.
Thank you
I had the same issue with the personnal hospot modifying the status bar.
The solution is to register to the system notification for the change of status bar frame, this will allow you to update your layout and should fix any layout issue you might have.
My solution which should work exactly the same for you is this :
In your view controller, in viewWillAppear suscribe to the UIApplicationDidChangeStatusBarFrameNotification
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(myControllerName.handleFrameResize(_:)), name: UIApplicationDidChangeStatusBarFrameNotification, object: nil)
Create your selector method
func handleFrameResize(notification: NSNotification) {
self.view.layoutIfNeeded() }
Remove your controller from notification center in viewWillDisappear
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidChangeStatusBarFrameNotification, object: nil)
You also need your modal to be in charge of the status bar so you should set
destVC.modalPresentationCapturesStatusBarAppearance = true
before presenting the view.
You can either implement this on every controller susceptible to have a change on the status bar, or you could make another class which will do it for every controller, like passing self to a method, keep the reference to change the layout and have a method to remove self. You know, in order to reuse code.
I think this is a bug in UIKit. The containerView that contains a presented controller's view which was presented using a custom transition does not seem to move back completely when the status bar returns to normal size. (You can check the view hierarchy after closing the in call status bar)
To solve it you can provide a custom presentation controller when presenting. And then if you don't need the presenting controller's view to remain in the view hierarchy, you can just return true for shouldRemovePresentersView property of the presentation controller, and that's it.
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
return PresentationController(presentedViewController: presented, presenting: presenting)
}
class PresentationController: UIPresentationController {
override var shouldRemovePresentersView: Bool {
return true
}
}
or if you need the presenting controller's view to remain, you can observe status bar frame change and manually adjust containerView to be the same size as its superview
class PresentationController: UIPresentationController {
override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) {
super.init(presentedViewController: presentedViewController, presenting: presentingViewController)
NotificationCenter.default.addObserver(self,
selector: #selector(self.onStatusBarChanged),
name: .UIApplicationWillChangeStatusBarFrame,
object: nil)
}
#objc func onStatusBarChanged(note: NSNotification) {
//I can't find a way to ask the system for the values of these constants, maybe you can
if UIApplication.shared.statusBarFrame.height <= 20,
let superView = containerView?.superview {
UIView.animate(withDuration: 0.4, animations: {
self.containerView?.frame = superView.bounds
})
}
}
}
I've been looking for a solution to this problem. In fact, I posted a new question similar to this one. Here: How To Avoid iOS Blue Location NavigationBar Messing Up My StatusBar?
Believe me, I've been solving this for a couple of days now and it's really annoying having your screen messed up because of the iOS's status bar changes by in-call, hotspot, and location.
I've tried implementing Modi's answer, I put that piece of code in my AppDelegate and modified it a bit, but no luck. and I believe iOS is doing that automatically so you do not have to implement that by yourself.
Before I discovered the culprit of the problem, I did try every solution in this particular question. No need to implement AppDelegate's method willChangeStatusBar... or add a notification to observe statusBar changes.
I also did redoing some of the flows of my project, by doing some screens programmatically (I'm using storyboards). And I experimented a bit, then inspected my previous and other current projects why they are doing the adjustment properly :)
Bottom line is: I am presenting my main screen with UITabBarController in such a wrong way.
Please always take note of the modalPresentationStyle. I got the idea to check out my code because of Noah's comment.
Sample:
func presentDashboard() {
if let tabBarController = R.storyboard.root.baseTabBarController() {
tabBarController.selectedIndex = 1
tabBarController.modalPresentationStyle = .fullScreen
tabBarController.modalTransitionStyle = .crossDissolve
self.baseTabBarController = tabBarController
self.navigationController?.present(tabBarController, animated: true, completion: nil)
}
}
I solve this issue by using one line of code
In Objective C
tabBar.autoresizingMask = (UIViewAutoResizingFlexibleWidth | UIViewAutoResizingFlexibleTopMargin);
In Swift
self.tabBarController?.tabBar.autoresizingMask =
UIViewAutoresizing(rawValue: UIViewAutoresizing.RawValue(UInt8(UIViewAutoresizing.flexibleWidth.rawValue) | UInt8(UIViewAutoresizing.flexibleTopMargin.rawValue)))`
You just need to make autoresizingMask of tabBar flexible from top.
In my case, I'm using custom presentation style for my ViewController.
The problem is that the Y position is not calculated well.
Let's say the original screen height is 736p.
Try printing the view.frame.origin.y and view.frame.height, you'll find that the height is 716p and the y is 20.
But the display height is 736 - 20(in-call status bar extra height) - 20(y position).
That is why our view is cut from the bottom of the ViewController and why there's a 20p margin to the top.
But if you go back to see the navigation controller's frame value.
You'll find that no matter the in-call status bar is showing or not, the y position is always 0.
So, all we have to do is to set the y position to zero.
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let f = self.view.frame
if f.origin.y != 0 {
self.view.frame = CGRect(x: f.origin.x, y: 0, width: f.width, height: f.height)
self.view.layoutIfNeeded()
self.view.updateConstraintsIfNeeded()
}
}
Be sure to set the frame of the view controller's view you are presenting to the bounds of the container view, after it has been added to the container view. This solved the issue for me.
containerView.addSubview(toViewController.view)
toViewController.view.frame = containerView.bounds

Hide tab bar in IOS swift app

I'm trying to figure out how to hide the tab bar in my iOS swift app. I don't care about any fancy animations or anything. Just something I can put in the ViewDidLoad() function.
You can simply use this in your ViewDidLoad() method.
self.tabBarController?.tabBar.hidden = true
For Swift 3.0, 4.0, 5.0:
self.tabBarController?.tabBar.isHidden = true
Or you can change z position of tab bar this way:
self.tabBarController?.tabBar.layer.zPosition = -1
and if you want to show it again then:
self.tabBarController?.tabBar.layer.zPosition = 0
The accepted answer works, but the transition to other view has a choppy animation (The tab Bar animation)
Also wanted to add although Kalpesh's solution worked perfectly for me, I found out that every view controller has an attribute for hidesBottomBarWhenPushed (check out storyboard.) If you wish to hide tab bar, you should put a tick on that. And it would work great.
Update: Im not sure if this is a known thing, but here's what apple documentation page says:
A view controller added as a child of a navigation controller can
display an optional toolbar at the bottom of the screen. The value of
this property on the topmost view controller determines whether the
toolbar is visible. If the value of this property is true, the toolbar
is hidden. If the value of this property is false, the bar is
visible.
I think this means that you have to set the basic value of hidesBottomBarWhenPushed at the topmost view controller (the first one on the navigation stack.) Once you have set that to true, you can change to false or true for the other viewcontrollers on the stack. But, if your topmost view controller's hidesBottomBarWhenPushed value is false, it will not show a tab bar for other controllers on the navigation stack.
Before push set controller.hidesBottomBarWhenPushed = true
let objCreateEventVC = CreateEventVC()
objCreateEventVC.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(objCreateEventVC, animated: false)
No need to set tabBar's isHidden property.
Simply, Go to ViewController (in StoryBoard) -> Attribute inspector -> Under 'View Controller' section select 'Hide Bottom Bar on Push' checkbox. This works like a charm.
If you go the 'isHidden' way you need to do a lot of handling, i.e. to make it appear again when you go back and also to remove the bottom empty space after hiding tabBar.
Swift 3.
self.tabBarController?.tabBar.isHidden = true
You can also set it in extension (use Dharmesh Kheni answer)
extension UITabBar {
func tabsVisiblty(_ isVisiblty: Bool = true){
if isVisiblty {
self.isHidden = false
self.layer.zPosition = 0
} else {
self.isHidden = true
self.layer.zPosition = -1
}
}
This is the way programmatically for Swift 4.0, 4.1, 4.2, 5.0 and later >:
tabBarController?.hidesBottomBarWhenPushed = true
or
hidesBottomBarWhenPushed = true
Hide & Show Tab Bar With Animation
For those looking to hide/show the tab bar with animation.
Since iOS 13, the behavior of the UITabBar has changed for animations. You can no longer use CGAffineTransform and instead you should animate its frame position.
See my full guide here: hide & show tab bar with animation
To hide the tab bar:
UIView.animate(withDuration: 0.7, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.7, options: .curveEaseOut) {
if let tabBarFrame = self.tabBarController?.tabBar.frame {
self.tabBarController?.tabBar.frame.origin.y = navigationController.view.frame.maxY + tabBarFrame.height
}
navigationController.view.layoutIfNeeded()
} completion: { _ in
self.tabBarController?.tabBar.isHidden = true
}
To show the tab bar:
UIView.animate(withDuration: 0.7, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.7, options: .curveEaseOut) {
if let tabBarFrame = self.tabBarController?.tabBar.frame {
self.tabBarController?.tabBar.frame.origin.y = navigationController.view.frame.maxY - tabBarFrame.height
}
navigationController.view.layoutIfNeeded()
}
Make sure to call layoutIfNeeded() inside the UIView.animate to trigger the changes with animation.
To hide the navigationBar and the tabBar I use the next function:
var tabBarHeight : CGFloat!
func fullScreenAction(){
if navigationController?.isNavigationBarHidden ?? false {
//Show navigationBar
navigationController?.setNavigationBarHidden(false, animated: false)
//Show tabBar
tabBarController?.tabBar.isHidden = false
//Update the height of tabBar
if (!(tabBarController?.tabBar.frame.size.height.isEqual(to: 0))!) {
tabBarHeight = self.tabBarController?.tabBar.frame.size.height
}
tabBarController?.tabBar.frame.size.height = tabBarHeight
} else {
//Hide navigationBar
navigationController?.setNavigationBarHidden(true, animated: false)
//Hide tabBar
tabBarController?.tabBar.isHidden = true
//Update the height of tabBar
tabBarHeight = tabBarController?.tabBar.frame.size.height
tabBarController?.tabBar.frame.size.height = 0
}
}
When the screen orientation has changed the height of tabBar change too, so I use the next function to exit of fullscreen to resize the height:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
if navigationController?.isNavigationBarHidden ?? false {
navigationController?.setNavigationBarHidden(false, animated: false)
tabBarController?.tabBar.isHidden = false
}
}
I hope it is useful for you.
Here is my code. it's just to hide its tabbar. (If no frames are well established there will be a black view at the bottom. )
var oldTabbarFr: CGRect = .zero
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
oldTabbarFr = self.tabBarController?.tabBar.frame ?? .zero
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.tabBar.isHidden = true
self.tabBarController?.tabBar.frame = .zero
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.tabBarController?.tabBar.isHidden = false
self.tabBarController?.tabBar.frame = oldTabbarFr
}

Resources