1

Background:

I am trying to organize my code for reuse. I like to keep a Utility class that handles all my button-clicking logic on Android, and am trying to do something similar with iOS.

I have a file called ButtonClicks with a static method ClickAction.

From a custom UIButton that I extended to add some data, I use the #selector inside the UIViewController.

Inside View Controller:

  button.addTarget(self, action: #selector(onClick(sender:)), for: .touchUpInside)

// ...

@objc func onClick(sender: Button){
    ButtonClicks.ClickAction(Button: sender)
}

This works pretty much as expected, with the exception of transitioning to new UIViewControllers when needed.

Question:

How can I open a new modal UIViewController from a utility class?

I'm currently passing a view object, so I have tried the following within the ButtonClicks class:

Class ButtonClicks {

static func ClickAction(Button: Button) {

...
// logic for sorting out which action to take
...

        let modalViewController = ModalViewController()
        modalViewController.modalPresentationStyle = UIModalPresentationStyle.formSheet
        modalViewController.modalTransitionStyle = UIModalTransitionStyle.coverVertical

        Button.superview?.window?.rootViewController?.present(modalViewController, animated: true, completion: nil)

This code starts a view controller that covers the entire screen in black, ignoring the .formSheet parameter and leaving the app covered in a black screen. It does print() logic from the ModalViewController to the debug area though.

Changing the presentationtyle to .partialCurl gives this error:

Application tried to present UIModalTransitionStylePartialCurl to or from non-fullscreen view controller

SQLiteNoob
  • 2,958
  • 3
  • 29
  • 44
  • what about passing your current view controller into the function so it can be used for presenting? – hakkurishian Nov 18 '17 at 19:47
  • so pass (Button: Button, UIViiewController: View) or something to the function? I'll try that. Do UI components not keep any reference to their view controllers? – SQLiteNoob Nov 18 '17 at 19:52
  • UIViews dont (and should not) keep this reference because they're supposed to be context-independent. See https://stackoverflow.com/questions/1372977/given-a-view-how-do-i-get-its-viewcontroller – hakkurishian Nov 18 '17 at 19:56
  • It works and is easier than I thought it would be. Write it as an answer and I'll up vote it. Vielen Danke. – SQLiteNoob Nov 18 '17 at 19:57

1 Answers1

1

You can pass your UIViewController to the onclick function such as:

 static func ClickAction(Button: Button, viewController: UIViewController) {
     //...
     viewController.present(...
}
hakkurishian
  • 266
  • 1
  • 3
  • 13