0

I have a ViewController that need to display in two places.

In first place, the VC need to present and dismiss using a cancel button in its navigation bar.

In second place, the VC need to push to a navigation stack(its presented modally too) and cannot close (user have to use the back button in navigation stack).

I can display the VC in both places correctly but cannot use the close button properly. When I add the cancel bar button item to the VC, it appears in both scenarios. How can I show the cancel button when the VC is presented and hide it when the VC is pushed?

nmy
  • 488
  • 8
  • 21
  • in `viewDidLoad` check if `self.presentingViewController` is nil or not, if its non nil than show cancel button else dont add any button to navigation bar – Sandeep Bhandari Feb 03 '21 at 12:25
  • @SandeepBhandari This added the cancel button to both. Maybe because of the VC is pushed to a navigation stack which is already presenting as modal. – nmy Feb 03 '21 at 14:10
  • Than why cant you use `self.navigationController?.presentingViewController != nil` ? – Sandeep Bhandari Feb 03 '21 at 14:18

1 Answers1

0

Using isBeingPresented you can manage your cancel button,

        if self.isBeingPresented {
           debugPrint("Controller is Presented")
        } else {
            debugPrint("Controller is Pushed")
         }
  • This doesn't add cancel button to the presented VC. Is it because VC is presented with a navigation controller? – nmy Feb 03 '21 at 14:14
  • Try below, If you have btn outlet btnCancel.isHidden = !self.isBeingPresented If it is nav bar btn try below self.navigationController.letBarButtonItem = self.isBeingPresented ? btnCancel : nil – ShashiKant_B Feb 04 '21 at 15:49
  • is it **absolutely** required for you to use the name 'Back' and 'Cancel' in two cases? Or what matters to you is just the **correct** functionality of dismissing VC in two different ways? If it is the last one, I can help you – Asol Feb 05 '21 at 13:53