calling a parent UIViewController method from a child UIViewController - ios

I have a Parent UIViewController, which opens a child UIViewController:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("myChildView") as! UIViewController
self.presentViewController(vc, animated: true, completion: nil)
I press a Button in the ChildView which should close the the ChildView and call a method in the Parent View:
self.dismissViewControllerAnimated(true, completion: nil)
CALL PARENTS METHOD ??????
How to do that ?
I found a good answer (Link to good answer), but I am not sure if this is the best practice with UIViewControllers. Can someone help ?

One easy way to achieve this you can use NSNotificationCenter for that.
In your ParentViewController add this into viewDidLoad method:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: Selector(("refresh:")), name:NSNotification.Name(rawValue: "refresh"), object: nil)
}
After that add this function in ParentViewController which will get called when you dismiss your ChildViewController:
func refreshList(notification: NSNotification){
print("parent method is called")
}
and into your ChildViewController add this code where you dismissing your child view:
#IBAction func btnPressed(sender: AnyObject) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refresh"), object: nil)
self.dismiss(animated: true, completion: nil)
}
Now when you dismiss child view refreshList method will be call.

Add a weak property to the child view controller that should contain a reference to the parent view controller
class ChildViewController: UIViewController {
weak var parentViewController: UIViewController?
....
}
Then in your code (I'm assuming it's inside your parent view controller),
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("myChildView") as! ChildViewController
vc.parentViewController = self
self.presentViewController(vc, animated: true, completion: nil)
And, as vomako said, call the parent's method before dismissing your child view controller.
parentViewController.someMethod()
self.dismissViewControllerAnimated(true, completion: nil)
Or, you can also call the method in the completion paramter of dismissViewControllerAnimated, where it will be run after you child view controller dismisses:
self.dismissViewControllerAnimated(true) {
parentViewController.someMethod()
}

Something that I've noticed in your question: Do not call a method (the parent method in your case) after dismissing the view controller. Dismissing the view controller will cause it to be deallocated. Later commands may not be executed.
The link that you've included in your question points to a good answer. In your case, I would use delegation. Call the delegation method in the parent view controller before you dismiss the child view controller.
Here is an excellent tutorial.

protocol SampleProtocol
{
func someMethod()
}
class parentViewController: SampleProtocol
{
// Conforming to SampleProtocol
func someMethod() {
}
}
class ChildViewController
{
var delegate:SampleProtocol?
}
self.dismissViewControllerAnimated(true, completion: nil)
delegate?.someMethod()

Related

Show second modal view controller after first was closed

I have two view controller that opens modally. When the first VC closed then the second should be opened. But when I close the first one, the second one is not displayed at all.
what is the problem?
My code is:
self.dismiss(animated: true) {
let flowVC = LanguageFlowViewController()
self.present(flowVC, animated: true)
}
You need reference of view controller from where you to present first view controller.
For example, you have view controller name as X, from there your first view controller A present. So you need reference of X to present B, because A will not be available in memory.
So when you try to present second view controller using self, it will do nothing.
So, for solution assign reference of X view controller to A. In class A, declare:
var refX: X?
While present A from X, set self to refX. Like:
var aVC = A() // This is temp, you need to instantiate your view controller here.
aVC.refX = self
self.present(aVC, animated: true, completion: nil)
Now, inside view controller A, when dismiss:
var bVC = B() // This is temp, you need to instantiate your view controller here.
self.dismiss(animated: true) {
if self.refX != nil {
self.refX?.present(bVC, animated: true, completion: nil)
}
}
I hope this will help you.
If you want to open modally ThirdViewController after Dismiss SecondViewController then you have to create protocol for it.
Like we have three UIViewController(FirstViewController,SecondViewController and
ThirdViewController)
Step 1: We need to create a protocol in SecondViewController as given below code.
protocol DismissedViewProtocal {
func dismissView()
}
class SecondViewController: UIViewController {
var delegate: DismissedViewProtocal?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func dismissSecondViewAction(_sender : AnyObject) {
dismiss(animated: true) {
self.delegate?.dismissView()
}
}
Step 2: You need to add protocol in FirstViewController as given below
class FirstViewController: UIViewController, DismissedViewProtocal {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func anAction(_sender : AnyObject){
let flowVC = self.storyboard?.instantiateViewController(withIdentifier:"SecondViewController") as? SecondViewController
secondVC?.delegate = self
self.present(secondVC!, animated: true) {
}
}
func dismissView() {
let thirdVC = self.storyboard?.instantiateViewController(withIdentifier:"ThirdViewController")
self.present(thirdVC!, animated: true) {
}
}
}
Your are dismissing the current view controller by calling self.dismiss().
Therefore it is impossible for it to present anything anymore, since it is removed from the view hierarchy. As others have mentioned, try using the self.presentingViewController or self.navigationController (if it is on a navigationController) to present your new view.
However, if you need maximum flexibility create a delegate protocol. Create a protocol with a function presentForChild(viewController: UIViewController). Before your previous view presents the view from which the code in your question belongs to, give it a reference of the protocol.
Example:
protocol ChildPresentDelegate: class {
func presentForChild(vc: UIViewController)
}
class FirstController: UIViewController, ChildPresentDelegate {
func presentForChild(vc: UIViewController) {
present(vc, animated: true, completion: nil)
}
/**
other code
*/
func showControllerAsWasShownInTheQuestion() {
let controller = SecondController()
controller.delegate = self
present(controller, animated: true, completion: nil)
}
}
class SecondController: UIViewController {
weak var delegate: ChildPresentDelegate?
func dismissMySelf() {
self.dismiss(animated: true) {
delegate?.presentForChild(vc: LanguageFlowViewController())
}
}
}

how can I dismiss first vc that second has presented modally on the first vc

I have a view controller that named "firstVC" and another one that named "secondVC" . the secondVC will present modally on the first vc I want to dismiss firstVC and secondVC when user push the button on the secondVC
I call the method here But it does execute But nothing will happen
in the secondVC this will happen
firstVC.dismiss(animated: true, completion: nil)
if you suggest me to use delegate please tell me how can I use that completely ? I don't know what should I put in the firstVC or what should I put in the secondVC
one more thing
In some other cases I need to execute json in the firstVC and when json has complete the both view controllers (firstVC and secondVC) be dismiss how can I do that too ?
Here is a solution using delegate:
protocol DismissDelegate{
func dismissVC()
}
class FirstViewController: UIViewController, DismissDelegate{
func showSecondVC(){
let secondVC = SecondViewController()
secondVC.delegate = self
}
func dismissVC(){
self.dismiss(animated: true, completion: nil)
}
}
class SecondViewController: UIViewController{
var delegate: DismissDelegate?
#IBAction func buttonAction(sender: UIButton){
self.dismiss(animated: true, completion: nil)
delegate?.dismissVC()
}
}

How to present another view controller after dismiss from navigation controller in swift?

How to present another view controller after dismiss from navigation controller in swift ?
I am using Navigation controller.
ViewController1.swift
func pushTo(viewController: UIViewController) {
let showLocalPwd = self.storyboard?.instantiateViewController(withIdentifier: "LocalPwdVC") as! LocalPwdVC
self.navigationController?.present(showLocalPwd, animated: true, completion: nil)
}
ViewController2.swift
#IBAction func btnVerify(_ sender: Any)
{
self.dismiss(animated: true, completion: {
let vc = self.storyboard.instantiateViewController(withIdentifier: "DataVC") as! DataVC
self.navigationController.pushViewController(vc, animated: true)
})
}
After dismissing the View Controller, it will not goes to next viewcontroller i.e. DataVC
If you want to present the view controller then create a protocol in your dismissViewController
protocol dismissViewController {
func presentCompletedViewController()
}
// Then create a delegate
var delegate = dismissViewController? = nil
// If you are using action to dismiss your ViewController then call delegate
#IBAction func YourButton(_ sender: Any) {
self.dismiss(animated: true) {
self.delegate!.presentCompletedViewController()
}
}
//And then call this in your main or homeViewController
class HomeViewController: UIViewController, dismissViewController {
func presentCompletedViewController(){
// enter code to present view controller
}
// And at last don't forget to call delegate
yourVc.delegate = self
you need to call this delegate in which you are presenting your dismissViewController

Dismiss second ViewController from the third ViewController

I am trying to dismiss VC b from VC c where VC c is a popover and has a button for sign out but it is not working.
The structure of the flow is
VC a ----presents modally----> VC b ----presents a popover----> VC c
When the button in the popover is clicked the VC c and VC b must be dismissed so that (VC a)ViewWillAppear is called.
Try this:
You can dismiss your presentingViewController from child view controller as follow
self.presentingViewController?.dismiss(animated: true, completion: nil)
When you add a ViewController as childViewController
self.parent?.dismiss(animated: true, completion: nil)
If this view controller is a child of a containing view controller (e.g. a navigation controller or tab bar
controller,)
weak open var parent: UIViewController? { get }
The view controller that was presented by this view controller or its nearest ancestor.
open var presentedViewController: UIViewController? { get }
The view controller that presented this view controller (or its farthest ancestor.)
open var presentingViewController: UIViewController? { get }
If ViewControllers have hierarchy like
VC a ----presents as self.present(objects, animated: true, completion: nil) modally----> VC b ---- presents as self.present(objects, animated: true, completion: nil) popover----> VC c
And there are a button on VC c to move back to VC a then you can use:
self.presentingViewController?.presentingViewController?.dismiss(animated: true, completion: nil)
First of all try to dismiss VC b from itself, not presenting the VC c just to check if it works, using: self.dismiss(animated: true, completion: nil) or if VC b is embedded in a navigation controller, like this: self.navigationController?.dismiss(animated: true, completion: nil)
If the one from above works, I would suggest you implement the delegation protocol, where VC c will delegate to VC b the dismissal, whenever it should be done. You could also use a completion block for that, containing the dismiss code.
Hope this works
// Call inside View controller C
self.presentingViewController?.dismissViewControllerAnimated(false, completion: nil)
self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
`protocol ModalHandler {
func modalDismissed()
Class SecondViewController: UIViewController, ModalHandler {
func modalDismissed() {
self.dismiss(animated: false, completion: nil)
}
func open3rdController() {
let thirdVC = ThirdViewController(_ )
thirdVC.delegate = self
self.present(thirdVC, animated: true, completion: nil)
}
class ThirdViewController: UIViewController {
func dismiss() {
self.delegate.modalDismissed()
}
}
`
Whats about a Presenter or a Coordinator.
This instance will initialize all these VCs and also present them.
From there you can also dismiss them.

Pop a navigation controller

I have two views, V1 and V2. I want to "present" V2 when the add button is pressed on V1, and "pop" V2 off when the stop button is pressed, so that the original V1 is the top of the stack.
From what I have read, I need a separate view controller for V2. From the limited information I could find, I need V1's view controller to conform to V2's protocol, V2delegate. This is what I have, but it is not working:
ViewController1 with V1
class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout, FormViewControllerDelegate {
let form = FormViewController()
func addTapped() {
form.delegate = self
let nav = UINavigationController(rootViewController: form)
navigationController?.present(nav, animated: true)
}
func popForm() {
navigationController?.popViewController(animated: true)
navigationController?.popToViewController(self, animated: true)
print("popped")
}
}
ViewController2 with V2
class FormViewController: UIViewController {
var delegate: FormViewControllerDelegate?
func stopTapped() {
print("pop it")
delegate?.popForm()
}
}
protocol FormViewControllerDelegate {
func popForm()
}
What am I doing wrong here?
In your VC2, Change to use this code
func stopTapped() {
print("pop it")
self.dismiss(animated: true, completion: nil)
}
Use this in ViewController1 to present FormViewController
func addTapped() {
let nav = UINavigationController(rootViewController: form)
self.present(nav, animated: true)
}
Within FormViewController when want to dismiss use this
func stopTapped() {
self.dismiss(animated: true)
}
You have presented the ViewController not pushed the ViewController, so what you need is to dismiss the Controller instead of pop the controller from navigation stack.
func popForm() {
navigationController?.dismiss(animated: true)
print("popped")
}
Better if you renamed the method name to dissmissForm instead of popForm.
You need to dismiss VC2 instead of pop. in self class as below :
func stopTapped() {
self.dismiss(animated: true, completion: { _ in })
}
When you are presenting any viewcontroller then you must use dismissViewController method to remove presented view controller. popViewController is used when you hqve push any viewcontroller.
When you use present then you have to use dismiss to remove that currently presented class in stack, when you dismiss it, your just next previous class will be in top of the stack. Thats all.. hope, it may helps you.
for pop a UIViewController you nee to push and not present. If you need to present a UIViewVontroller then on click on "X" you need to dismiss that viewController.
For push view controller
func addTapped() {
self.navigationController?.pushViewController(from, animated: true)
}
func stopTapped() {
self.navigationController?.popViewController(animated: true)
}
For presenting a view controller
func addTapped() {
self.present(from, animated: true, completion: nil)
}
func stopTapped() {
self.dismiss(animated: true, completion: nil)
}
You don't need to code for any protocol to push or present a UIViewController

Resources