Why viewDidLoad function is not called? - ios

I want to change UIBarButton's color in the navigationBar. To achieve this, in viewDidLoad: I put this line:
navigationController?.navigationBar.tintColor = .white
Everything works fine until I started to notice something strange. That UIBarButton is used to dismiss the UIViewController. When it is pressed, I just dismiss the viewController. But, if I present it (viewController) again, the color of the UIBarButton is not white, it gets tintColor of the application.
After doing some debugging, I noticed that viewDidLoad: is not called again after the viewController is just dismissed and presented again. The reason why my UIBarButton has a different color is because I change its color in viewDidLoad:. When viewDidLoad: is not called, of course, color is not changed.
It was an interesting discovery for me the fact that iOS doesn't call viewDidLoad: for UIViewController that was presented already. Possibly, it is due to the optimisation, because it is not efficient to draw the whole UI every time.
My solution to this problem can be to change color, not in viewDidLoad:, but in viewDidAppear:. But, is it right approach to solve a problem? And why viewDidLoad: is not called in the above situation?

It looks like you create and store you view controller, but present it wrapped in UINavigationController:
let controller = YourModalViewController()
...
func presentMyModal() {
present(UINavigationController(rootViewController: controller))
}
In this case your viewDidLoad method will be called just once and you'll have visual bug. If you want to leave styling code of your modal inside it's file you can create instance func which will return this controller wrapped and styled.
extension YourModalViewController {
func wrappedInNC() -> UINavigationController {
let nc = UINavigationController(rootViewController: controller)
// Styling code.
return nc
}
}

Related

How to change UIWindow background color through a view controller

This question is really similar to this: How to set an app's UIWindow color when calling it from ViewController. However, the solutions there aren't working.
Ever since apple changed the window to be located in the scene delegate (instead of the app delegate) I haven't been able to change the window (UIWindow) background color outside of scene delegate (using the methods in the article above). Is there any way to either call a function inside of Scene Delegate (through a view controller) or to change the window background color in a view controller. The reason I need this feature is because I handle my themes inside of the app, and when the user changes the theme I need the UIWindow background color to also change (for all of my app) for any cases where the UIWindow color shows (ex: presenting a view controller). A solution which I've tried is:
if let window = UIApplication.shared.delegate?.window as? UIWindow {
window.backgroundColor = .red
}
But it doesn't work for me.
You can change it in any controller like this
override func viewDidAppear(_ animated: Bool) {
view.window?.backgroundColor = .red
}

Navigation bar buttons set during viewDidLoad don't appear until after view has appeared in iOS 11

In iOS 10, I could determine the list of navigation bar buttons I want to appear in viewDidLoad, and they would appear in the navigation bar as the view controller transitioned in.
In iOS 11, I can no longer do this. Whatever navigation bar buttons were set in interface builder are displayed as the view controller transitions in, and my custom list of buttons are not displayed until after the view finishes sliding in. Updating the buttons in viewWillAppear does not help.
Is this simply a bug in iOS 11, or is there something else I should be doing? Is there a workaround so I can continue to display buttons while the screen loads?
In the following example, I have set a button "Default Button" in the storyboard, and override it with an "Edit" button in viewDidLoad. The project is available on Github.
iOS 10
iOS 11
It looks like the issue is that navigation bar icons displayed during the transition appear to be fixed when the view controller is passed off to the navigation controller. By the time that viewDidLoad is called, the icons have already been fixed.
In order to fix this, we need to update the navigation bar icons on the view controller's navigationItem before the view controller is pushed onto the navigation controller stack.
One way to do this would be to setup the navigation bar icons in awakeFromNib. This is what #Joe's answer was effectively doing, because apparently viewDidLoad is called from awakeFromNib when isViewLoaded is true during awakeFromNib.
However, doing this in awakeFromNib prevents you from taking into account any properties set on the view controller in prepareForSegue. So another option (and the one that I am using) is to force the entire view to load in prepareForSegue by adding the line _ = controller.view after setting any desired properties.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = tableView.indexPathForSelectedRow {
let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
...
_ = controller.view
}
}
}
Move your Edit barButton code from viewDidLoad to isViewLoaded method as below.
override var isViewLoaded: Bool {
self.navigationItem.rightBarButtonItem = self.editButtonItem
return true
}
Output:
Note: Above code will fix the transition delay issue. Really, don't have much to explain why this happening. I experienced similar issue in iOS 10 as well NavigationBar delay updating barTintColor iOS10. It could be another bug in iOS11.
PS:
After reading Apple Doc about isViewLoaded and comparing other view loading methods. Its all about loading memory upon view loads.
You don't really need to move you barButton code at all.Just implement the isViewLoaded method and return to true as below:
override var isViewLoaded: Bool { return true}

Swift Modal View Controller with transparent background [duplicate]

This question already has answers here:
Transparent background for modally presented viewcontroller
(5 answers)
Closed 7 years ago.
I know this topic is quite popular, but I'm a little iniciate problem in a programming language, the fact is that I still do not understand where I put the code. Well, I'll tell the whole case:
I'm trying to make a modal Swift in a little different from normal: By clicking on a button, the ViewController is displayed (following modal type) on the screen, but with transparent background. Only the blue View with label will be displayed. When this ViewController is presented, it is with transparent background, but as soon as it completes the transition, it will stay with the black background. Already deactivated the opaque option, and tested some options, but nothing this troubleshooting.
Some can help me?
The video is a test in the simulator on the case (https://www.youtube.com/watch?v=wT8Uwmq9yqY).
I'm starting with swift, and I'm still pretty lost with how to program in Xcode, I read an answer to a question that has the following code to solve this:
self.presentingViewController.providesPresentationContextTransitionStyle = YES;
self.presentingViewController.definesPresentationContext = YES;
modal.modalPresentationStyle = UIModalPresentationOverCurrentContext;
Where do I put this code?
You can do it like this:
In your main view controller:
func showModal() {
let modalViewController = ModalViewController()
modalViewController.modalPresentationStyle = .overCurrentContext
presentViewController(modalViewController, animated: true, completion: nil)
}
In your modal view controller:
class ModalViewController: UIViewController {
override func viewDidLoad() {
view.backgroundColor = UIColor.clearColor()
view.opaque = false
}
}
If you are working with a storyboard:
Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:
Background = Clear Color
Drawing = Uncheck the Opaque checkbox
Presentation = Over Current Context
As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

Insert subview behind TabBar from child view of TabBarController

I have TabBar with 2 tabs. At some point, from either of the 2 tabs, I want to add a view that is visible on both tab views but behind the TabBar.
So I thought, insert a subview into the TabBarController but below the TabBar.
This works fine in principle and I have the view behind the TabBar but now covering my 2 tabs as I wanted. However, it doesn't actually load. Just its background loads and only viewDidLoad() is called, not viewWillAppear() or any others.
I have also tried calling addChildViewController(myVC) on the TabBarController which has no effect, and also manually calling viewWillAppear() on the view controller I add which also has no effect (and I'm also dubious about whether manually calling viewWillAppear() is permitted or not?).
Is what I'm trying to do possible? What am I missing? Or should I be attempting this some other way?
For some reason, when inserting a subview into a UITabBarController behind it's UITabBar, although the view is visible to the user, the system itself seems to think it is not and so although viewDidLoad() is called, viewDidAppear() and subsequent methods are not.
However, adding a subview above the UITabBar seems to work fine. So I solved this by adding my own new UITabBar as a subview to the UITabBarController (set up basically exactly as the default one would be) and then removing the UITabBarController's default UITabBar.
Then when later inserting my view into the UITabBarController, I insert it as I was doing originally but instead below/behind my custom UITabBar and it seems to load fine.
There is no need to remove and recreate the tabBar. What you need to do is after you insert your custom view, you can then bring the tabBar to the front again.
//bring the tabBar to the front after inserting new view
self.view.bringSubview(toFront: self.tabBar)
This would be a good way:
Add the function below and call it in viewDidLoad of your initial VC. It unwraps your tab bar controller instance (which is optional), and then inserts the view you always want visible just below the tab bar.
private func setupAlwaysVisibleView() {
guard let tabBarController = self.tabBarController else { return }
tabBarController.view.insertSubview(alwaysVisibleView, belowSubview: tabBarController.tabBar)
}
Avoid using optionals for tabBarController or removing current tabBar. Simple add your view below tabBar view. Swift 5, XCode 11.
class TabBarController: UITabBarController {
#IBOutlet var instructionsView: UIView!
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.view.insertSubview(instructionsView, belowSubview: self.tabBar)
}
}
you can also do this inside the init() method for your UITabViewController:
view.insertSubview(alwaysVisibleView, belowSubview: self.tabBar)
no need to dispatch to another method if you are using a subclass of UITabViewController.

Disable swipe back gesture in Swift

Been looking around on here for a while but can't seem to find a working solution.
I'm trying to disable the swipe to go back to previous view gesture, in Swift.
I've tried a variety of solutions including:
self.navigationController?.interactivePopGestureRecognizer.enabled = false
and
self.navigationController.interactivePopGestureRecognizer.delegate = self
func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer!) -> Bool {
return false
}
Is there a new method of doing this or some other method that works?
The following is an easy approach to disabling & re-enabling the swipe back.
Swift 3.x & up
In a viewDidLoad/willAppear/didAppear method add:
navigationController?.interactivePopGestureRecognizer?.isEnabled = false
Just keep in mind that if you do it with viewDidLoad, then the next time you open the view, it may not be set depending upon whether or not it remains in your stack.
Unless you want it to remain off, you will need to turn it back on when the view is closed via either willMove(toParentViewController:) or willDisappear. Your navigationController will be nil at viewDidDisappear, so that is too late.
navigationController?.interactivePopGestureRecognizer?.isEnabled = true
A special note on SplitViewControllers:
As pointed out by CompC in the comments, you will need to call the second navigation controller to apply it to a detail view as such:
navigationController?.navigationController?.interactivePopGe‌​stureRecognizer?.isE‌​nabled = false
Swift 2.2 & Objective-C
Swift versions 2.x & below:
navigationController?.interactivePopGestureRecognizer?.enabled
Objective-C:
self.navigationController.interactivePopGestureRecognizer.enabled
You could disable it but that would not be to recommended as most iOS users go back by swiping and less by pressing the back button.
If you want to disable it it would be more reasonable to use a modal segue instead of a push segue which is not that big of a transfer.
If you really want to get rid of the swipe to go back function I would just disable the back button and have a done button on the top right of the screen.
self.navigationController?.navigationItem.backBarButtonItem?.isEnabled = false;
I was able to do this by returning false in gestureRecognizerShouldBegin
class ViewController2: UIViewController, UIGestureRecognizerDelegate {
...
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationController?.interactivePopGestureRecognizer.delegate = self
}
func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
Add this line before pushing view controller to navigation controller
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
Nothing wrong with either answer from Hari or Stefan but this is more succinct. Just put it in viewDidLoad and you're done.
if navigationController!.respondsToSelector(Selector("interactivePopGestureRecognizer")) {
navigationController!.view.removeGestureRecognizer(navigationController!.interactivePopGestureRecognizer)
}
EDIT:
One small caveat is that if the Navigation Controller was opened by another view and the Navigation Controller is closed then you'll get an EXC_BAD_ACCESS error. To fix it you have to save the original UIGestureRecognizer and put it back when you exit the view.
Declare:
private var popGesture: UIGestureRecognizer?
Immediately before removing the gesture:
popGesture = navigationController!.interactivePopGestureRecognizer
Then when closing the view:
If popGesture != nil {
navigationController!.view.addGestureRecognizer(popGesture!)
}
RowanPD's logic for Swift 4
private var popGesture: UIGestureRecognizer?
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if navigationController!.responds(to: #selector(getter: UINavigationController.interactivePopGestureRecognizer)) {
self.popGesture = navigationController!.interactivePopGestureRecognizer
self.navigationController!.view.removeGestureRecognizer(navigationController!.interactivePopGestureRecognizer!)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if let gesture = self.popGesture {
self.navigationController!.view.addGestureRecognizer(gesture)
}
}
Instead of
self.navigationController.pushViewController(VC, animated: Bool)
call
self.navigationController.setViewContollers([VC], animated: Bool)
setViewControllers replaces the all the VCs on the stack, instead of adding a new controller on top. This means that the new set VC is the root VC, and the user cannot go back.
This is most effective when you only want to disable the swipe on a single VC, and keep the swipe-to-back for the other VC.
If you want users to be able to go back, just not through swiping, do not use this method as it will disable all backs (as there is no VC to go back to).
for objective -c
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:true];
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
This is something you missed if it doesn't work after you tried all.
Add navigationController?.interactivePopGestureRecognizer?.isEnabled = false
to your viewWillAppear(animated:) method.
if it doesn't work, remove navigation delegate from the view controller. Check again if your view controller is confirming UINavigationControllerDelegate, UIGestureRecognizerDelegate protocols. if so, just remove it.
I generally make sure that swipe back is enabled in as many places as possible, even adding a custom gesture recognizer to add it to modal screens. However for an authentication and download process in my app I start the process with a modal navigation controller and then push the view for each next step. However, once it's completed I want to prevent them from backing up into the authentication screens.
For this scenario I've been using:
navigationController?.interactivePopGestureRecognizer?.isEnabled = false
navigationItem.hidesBackButton = true
in viewWillAppear() on the final screen. You can undo these in viewWillDisappear() if you're pushing another view and need them there.
Come here a little bit late. In my case self.navigationController?.navigationItem.backBarButtonItem?.isEnabled = false; not working. So I do this: you can present view controller instead of push view controller. This way the swipe back gesture will not apply to the view controller.
navigationController?.present(vc, animated: true)
You could use dismiss for your custom back button
self.dismiss(animated: true)
Note: You could set VC modal presentation style before present it to make sure it's full screen.
vc.modalPresentationStyle = .fullScreen
Hope this help.
If requirement is to show side menu on some of the screens then add AddScreenEdgePanGesture on this specific view instead of navigationController view
replace it
SideMenuManager.default.menuAddScreenEdgePanGesturesToPresent(toView: self.navigationController?.view)
with this
SideMenuManager.default.menuAddScreenEdgePanGesturesToPresent(toView: self.view)
Only complete removal of the gesture recognizer worked for me (from the presenting view controller).
if let navigationController = parent.navigationController,
let interactivePopGestureRecognizer = navigationController.interactivePopGestureRecognizer {
navigationController.view.removeGestureRecognizer(interactivePopGestureRecognizer)
}
Don't Use this if you don't want to come back, or you set the new rootViewController.
self.navigationController.pushViewController(VC, animated: Bool)
Use this
self.navigationController.setViewContollers([VC], animated: Bool)
setViewControllers Remove all the View Controllers on the stack then the user cannot go back. it will disable all backs
this worked for me
gesture(DragGesture(minimumDistance: 10, coordinateSpace: .global))
so minimum distance is the distance to which drag gesture start listening, setting to 0 removes any listening, but it will remove all interactions be aware, i have changed 0 to 10 to listen to tap gestures, but in your screen if you have any other interaction it will not work after adding this,
If you don't care about system back button appearance (for example, if you're using custom back button or navigation bar is hidden at all), it might help you:
navigationItem.hidesBackButton = true
It hides back button and disables swipe back gesture.

Resources