boolean variable automatically initializes when changing viewcontrollers in iOS - ios

In My application contain five different tabs. When I switch between tabs initialization of boolean variable automatically called again and again.
When I put a breakpoint on declaration/initialization variable it will be automatically called. This will leads to change my boolean variable value to true. Please go through the following code
How to resolve this issue. Please help me
class HomeViewController: BaseViewController {
var isEnabled: Bool = true
}
override func viewWillAppear(_ animated: Bool) {
isEnabled = true
}
override func viewWillDisappear(_ animated: Bool) {
isEnabled = false
}

You are using tab view for your app. When you switch from one tab to other tab viewWillAppear called and your boolean variable isEnabled is set to true and when move to new tab it called viewWillDisappear and set to false. If you don't want to change in isEnabled variable then remove from viewWillAppear and viewWillDisappear then value will not be changed. You will get last value assigned to variable.
viewDidLoad method will call only once a life time of viewController and that is when viewController object will first load in memory. where as viewWillAppear method will call every time when a view will appear to screen or you can say will be topViewController...
Explanation: Tab1 associated with viewController1 and tab2 is associated with viewController2. Now when you will run your app and you will see tab one is selected and viewController1 is on view and you want to change to tab2, when you will tap on tab2 then tabVieController2's object will create and load to memory first time hence its viewDidLoad method will call, and soon after that it will appear to window and viewWillAppear will also get call. Now if you you try changing tabs by click on them only viewWillAppear methods will get called for both, as they are in memory already.

Related

Viewcontroller does not work the second time it is called

Here is my code
self.slideMenuController()?.changeMainViewController(contactNVC, close: true)
contactNVC = ContactUsViewController.swift
contactNVC is working normally.
Go to another viewcontroller
Does not work when returning to contactNVC.
ContactUsViewController.swift
override func viewDidLoad() {
super.viewDidLoad()
print("ContactUsViewController is here")
}
First this "ContactUsViewController is here" will be printed.
When I call another view controller and come back to this ContactUsViewController.swift, this "ContactUsViewController is here" doesn't appear.
SlideMenuController /this is code from github/
https://github.com/dekatotoro/SlideMenuControllerSwift
self.slideMenuController()?.changeMainViewController(contactNVC, close: true)
You should use viewWillAppear() or viewDidAppear() method. These methods called every time your view controller is displayed on the screen.
Because viewDidLoad() is usually called once, when the VC is loaded. Sometimes it can be called multiple times. For example, if there is a memory warning sent, your VC will unload the view from memory, and the next time viewDidLoad() will be called again. But it will never be called consecutively. So just use viewWillAppear() or viewDidAppear() method, it will fire when view controller will be displayed, anyway.

UIStoryboardSegue animates property in subclass

I have a UIStoryboardSegue subclass for replacing current view controller with next view controller.
As we have a Animates property in interface editor, I want to access this property in the subclass.
My code is following:
class ReplaceSegue: UIStoryboardSegue {
override func perform() {
var viewControllers = source.navigationController?.viewControllers.dropLast() ?? []
viewControllers.append(destination)
source.navigationController?.setViewControllers(viewControllers.map {$0}, animated: true) // I dont want this `true` to be hardcoded
}
}
As per comments in UIStoryBoardSegue class
The segue runtime will call +[UIView setAnimationsAreEnabled:] prior
to invoking this method, based on the value of the Animates checkbox
in the Properties Inspector for the segue.
So obviously you can read the value of animate check box by using
UIView.areAnimationsEnabled
So in my custom segue
class MySegue: UIStoryboardSegue {
override func perform() {
debugPrint(UIView.areAnimationsEnabled)
}
}
This prints false if animate checkbox is unchecked or true if it is checked :)
So in your case
class ReplaceSegue: UIStoryboardSegue {
override func perform() {
var viewControllers = source.navigationController?.viewControllers.dropLast() ?? []
viewControllers.append(destination)
source.navigationController?.setViewControllers(viewControllers.map {$0}, animated: UIView.areAnimationsEnabled)
}
}
I hope whats happening is already clear, incase you still have doubt, here is the explanation, iOS checks the animates checkbox value and uses it to set whether animations are enabled or not by calling setAnimationsAreEnabled with the value of animates check box in interface prior to calling perform() method.
So when the control reaches inside perform you can be assured that iOS has already read the value of animates check box and used it to set setAnimationsAreEnabled all you have to do now is to ask areAnimationsEnabled to get the value of animates check box.
So that should provide you the value of animates checkbox :)
Hope it helps :)
You shouldn't need a UIStoryboardSegue subclass for this. The docs state "You can subclass UIStoryboardSegue in situations where you want to provide a custom transition between view controllers". This means that a replacement without without any animation isn't a custom transition, thus shouldn't use a segue subclass.
The correct way to do replacement is to use a Show Detail (e.g. Replace) segue and inside the parent view controller that is managing the child view controllers implement the method showDetailViewController and replace the children, e.g.
#implementation DetailNavigationController
- (void)showDetailViewController:(UIViewController *)vc sender:(id)sender{
[self setViewControllers:#[vc] animated:NO];
}
If you didn't know, the Show Detail segue (after magically instantiating the destination view controller) has a perform method that just calls showDetailViewController on self, and the base UIViewController implementation searches up the view controller hierarchy looking for one that overrides showDetailViewController, so you can intercept it and perform your custom code, before say it goes up to another parent that might implement it also like a split view.

How to call IBAction of another UIViewController soon after presentViewController?

So currently the user is in ViewController2, to transition to ViewController1 the presentViewController is being called.
Soon after ViewController1 opens up, there is an IBAction method that needs to be called.
How can this be accomplished? Any help would be greatly appreciated. Thank you!
The view controller can call it itself in either viewWillAppear or viewDidAppear.
self.myAction()
If the view controller is exclusively used in the context described you could do it unconditionally, otherwise if you need to do it conditionally - expose a Boolean:
public var doActionAfterAppear = false
public override viewDidAppear(animated isAnimated: Bool) {
super.viewDidAppear(animated: animated)
if self.doActionAfterAppear {
self.myAction()
self.doActionAfterAppear = false
}
}
And lastly before you present the second view controller or transition to it:
nextViewController. doActionAfterAppear = true

ViewDidLoad is always called

I just recently started to use Swift and am facing a "weird" bug with the viewDidLoad method.
My very simple app currently only has 2 viewcontrollers:
MainViewController, which is the Apps entry point and serves as an overview for the data which has already been created. It also provides the option to add new data, which would trigger a segue to
DataViewController, which provides the UI to create new data, after which it goes back to the MainViewController
Now my issue is that the viewDidLoad method of MainViewController is always called whenever the MainViewController appears (At the start of the app and every time the DataViewController disappears). Particularly, the msg "MainViewController newly created" is always printed.
Even worse, it seems that my app is "secretly" resetting. To show this I have defined the class variable "createView" in my MainViewController which is true by default, and is set to false during the viewDidLoad (the only place where this variable is called/set). However the msg "MVC newly created" is still always printed in the output after the MainViewController shows up. How can that be? Why / how is createView reset to true?
Hope this snippet is enough to find the issue. Otherwise, let me know if something is missing.
Thanks for your help!
override func viewDidLoad()
{
super.viewDidLoad()
if (createView)
{
determineArraySize()
createDataArray()
print("MainViewController newly created")
createView = false
}
else {print("Nothing happened")}
}
As #moritz mentioned in the comments, check out the way you present the DataViewController in your storyboard.
If the view is presented modally, you should call:
dismiss(animated: true, completion: nil)
If the view is presented using a show seque, you should call:
_ = navigationController?.popViewControllerAnimated(true)

Swift: Perform a function on ViewController after dismissing modal

A user is in a view controller which calls a modal. When self.dismissViewController is called on the modal, a function needs to be run on the initial view controller. This function also requires a variable passed from the modal.
This modal can be displayed from a number of view controllers, so the function cannot be directly called in a viewDidDisappear on the modal view.
How can this be accomplished in swift?
How about delegate?
Or you can make a ViewController like this:
typealias Action = (x: AnyObject) -> () // replace AnyObject to what you need
class ViewController: UIViewController {
func modalAction() -> Action {
return { [unowned self] x in
// the x is what you want to passed by the modal viewcontroller
// now you got it
}
}
}
And in modal:
class ModalViewController: UIViewController {
var callbackAction: Action?
override func viewDidDisappear(_ animated: Bool) {
let x = … // the x is what you pass to ViewController
callbackAction?(x)
}
}
Of course, when you show ModalViewController need to set callbackAction like this modal.callbackAction = modalAction() in ViewController
The answer supplied and chosen by the question asker (Michael Voccola) didn't work for me, so I wanted to supply another answer option. His answer didn't work for me because viewDidAppear does not appear to run when I dismiss the modal view.
I have a table and a modal VC that appears and takes some table input. I had no trouble sending the initial VC the modal's new variable info. However, I was having trouble getting the table to automatically run a tableView.reloadData function upon dismissing the modal view.
The answer that worked for me was in the comments above:
You likely want to do this using an unwind segue on the modal, that
way you can set up a function on the parent that gets called when it
unwinds. stackoverflow.com/questions/12561735/… – porglezomp Dec 15
'14 at 3:41
And if you're only unwinding one step (VC2 to VC1), you only need a snippet of the given answer:
Step 1: Insert method in VC1 code
When you perform an unwind segue, you need to specify an action, which
is an action method of the view controller you want to unwind to:
#IBAction func unwindToThisViewController(segue: UIStoryboardSegue) {
//Insert function to be run upon dismiss of VC2
}
Step 2: In storyboard, in the presented VC2, drag from the button to the exit icon and select "unwindToThisViewController"
After the action method has been added, you can define the unwind
segue in the storyboard by control-dragging to the Exit icon.
And that's it. Those two steps worked for me. Now when my modal view is dismissed, my table updates. Just figured I'd add this, in case anyone else's issue wasn't solved by the chosen answer.
I was able to achieve the desired result by setting a Global Variable as a boolean value from the modal view controller. The variable is initiated and made available from a struct in a separate class.
When the modal is dismissed, the viewDidAppear method on the initial view controller responds accordingly to the value of the global variable and, if needed, flips the value on the global variable.
I am not sure if this is the most efficient way from a performance perspective, but it works perfectly in my scenario.

Resources