swift presentViewController programmatically finds nil in destinationVC VDL

空扰寡人 提交于 2019-12-01 12:03:43

问题


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


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!