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)
create new swift file and create
TestViewControllerwith this code:class TestViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } func printHello(){ print("Hello World") } }Create new
UIViewControllerinmain.storyboardfile by clicking " " button in right top corner and typing "UIViewController"Assign
TestViewControlleras a class to your storyboardUIViewControllerAssign some identifier (TestIdentifier) to your storyboard
UIViewController
you can finally create
TestViewControllerinstance 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() }
