Home > Software design >  Calling subclass function from different class
Calling subclass function from different class

Time:03-17

I'm new to swift. How can I call func print on my CallerViewController class

   class CallerViewController: UIViewController {

       var subViewController: SubViewController!
       override func viewDidLoad() {
          super.viewDidLoad()
             subViewController = SubViewController() // this is throwing Missing argument for parameter 'coder' in call
             subViewController.printHello()
       }
   }

Subclass

   class SubViewController: SuperViewController {
       func printHello(){
          print("Hello World")
       }
   }

Super class

   class SuperViewController: UIViewController {
   }

CodePudding user response:

You can inherit the SubViewController in CallerViewController

 class CallerViewController: SubViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        printHello()
    }
}

class SubViewController: SuperViewController {
    func printHello() {
        print("Hello World")
    }
}

class SuperViewController: UIViewController {
    
}

CodePudding user response:

You are getting an error because you are not creating your UIViewController instance called SubViewController the correct way. Here is some guideline how to create UIViewController . For the sake of this guideline I call it TestViewController. Just to mention the guideline is using Storyboard based layout (as you do)

  1. create new swift file and create TestViewController with this code:

     class TestViewController: UIViewController {
    
       override func viewDidLoad() {
         super.viewDidLoad()
       }
    
       func printHello(){
         print("Hello World")
       }
     }
    
  2. Create new UIViewController in main.storyboard file by clicking " " button in right top corner and typing "UIViewController"

  3. Assign TestViewController as a class to your storyboard UIViewController

  4. Assign some identifier (TestIdentifier) to your storyboard UIViewController picture

  5. you can finally create TestViewController instance from storyboard by calling this function:

     func createUIViewControllerAndCallPrintHello() {
     let storyboard = UIStoryboard(name: "Main", bundle: nil)
     let testViewController =   storyboard.instantiateViewController(withIdentifier: "TestIdentifier") as! TestViewController
     testViewController.printHello()
     }
    
  • Related