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
TestViewController
with this code:class TestViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } func printHello(){ print("Hello World") } }
Create new
UIViewController
inmain.storyboard
file by clicking " " button in right top corner and typing "UIViewController"Assign
TestViewController
as a class to your storyboardUIViewController
Assign some identifier (TestIdentifier) to your storyboard
UIViewController
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() }