Trying to solidify my knowledge by understanding lines of code at a basic level.
I've tweaked my app to use ViewController(VC)2 as initial VC instead of VC1.
I'm practicing populating this VC2 entirely by code. When coding a UIButton to segue into VC1, my console outputs "fatal error: unexpectedly found nil while unwrapping an Optional value" (lldb). and thread 1 points to VC1 viewDidLoad (VDL) where I've set some properties
VC1
override func viewDidLoad() {
super.viewDidLoad()
P1Chip.hidden = true; P2Chip.hidden = true; P3Chip.hidden = true; P4Chip.hidden = true; P5Chip.hidden = true; P6Chip.hidden = true; P7Chip.hidden = true; P8Chip.hidden = true; P9Chip.hidden = true
etc
This VC1 was not having any problems with VDL when it was the initial VC.
method to populate VC2
import Foundation
import UIKit
class VC2: UIViewController {
let home:UIButton! = UIButton(frame: CGRectMake(10,10,15,15)) as UIButton
override func viewDidLoad() {
super.viewDidLoad()
home.backgroundColor = UIColor(red: 0.4, green: 0.6, blue: 0, alpha: 1)
home.setTitle("home", forState: .Normal)
home.addTarget(self, action: "home:", forControlEvents: .TouchUpInside)
view.addSubview(home)
}
func home(sender:UIButton!) {
self.presentViewController((VC1() as UIViewController), animated: true, completion: nil)
}
}
Any idea what I'm missing?
NOTE: btw VC2 is actually called Settings in my project
So when instantiating a VC (storyboard-created), first we need to route our call through the UIStoryboard by name
let storyboard = UIStoryboard(name: "Main", bundle: nil)
then instantiate a VC using the Storyboard ID of our storyboard setup VC
let vc = storyboard.instantiateViewControllerWithIdentifier("VC1") as VC1 //VC1 refers to destinationVC source file and "VC1" refers to destinationVC Storyboard ID
Then we can present VC using
self.presentViewController(vc, animated: true, completion: nil)
This will import all of destinationVC's objects with their IBOutlet references.
来源:https://stackoverflow.com/questions/29684581/swift-presentviewcontroller-programmatically-finds-nil-in-destinationvc-vdl