Reputation: 411
I am trying to create a subclass of UIViewController and then through the storyboard or programmatically pass data to it. What I have tried so far is to have a subViewController swift file with a class subViewController that is a UIViewController
import UIKit
class subViewController: UIViewController {
var s1 = String()
init(myString: String) {
self.s1 = myString
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
@IBOutlet var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
print(self.s1)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
then in Identity Inspector I connect this to the view controller
and in AppDelegate.swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let SubVC = subViewController(myString: "Komic")
self.window?.rootViewController = SubVC
self.window?.makeKeyAndVisible()
return true
}
This loads a black screen but it logs out myString. As far as I understand it doesn't create the view but it just creates the instance of the class and that's why it's giving me the black screen. I also know that this part
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
runs when the storyboard gives you the view. But I can't pass data in there that's why I am trying to do this programmaticaly. Is it possible somehow to do that? I know I could instantiateWithIdentifier with the storyboard but I can't find a way to pass my data through that....any help?
Upvotes: 2
Views: 1981
Reputation: 9206
An (ugly) way to solve this issue:
You can set your var s1
from an external buffer in your code (AppDelegate variable in this example)
required init?(coder aDecoder: NSCoder) {
self.s1 = UIApplication.shared().delegate.bufferForS1
super.init(coder: aDecoder)
}
And when you initiate your UIViewController through Storyboard:
UIApplication.shared().delegate.bufferForS1 = myS1Value
self.navigationController!.pushViewControllerFading(self.storyboard!.instantiateViewController(withIdentifier: "myViewControllerID") as UIViewController)
Upvotes: 2
Reputation: 2165
You are not loading the view controller from the storyboard when you call your custom initialiser, if you create a customer initialiser it is your responsibility to create the view hierarchy programatically - typically in loadView() although lots of people do it in viewDidLoad().
In Order to the load the view hierarchy you defined in the storyboard you can do this:
let storyBoard = UIStoryboard(name: "storyboardName", bundle: NSBundle.mainBundle())
let viewController = storyBoard.instantiateViewControllerWithIdentifier("storyboardId")
You define the storyboard Id of a view controller in the identity inspector
Upvotes: -1