Search code examples
swiftnulliboutlet

IBOutlet of another view controller is nil


I have a storyviewcontroller which has objects on its view. I need to change the text on the UILabel(In the storyviewcontroller) and the load the view on an array. I have connected the IBOutlet to the label in the storyviewcontroller.

class StoryViewController: UIViewController {
@IBOutlet weak var textLabel: UILabel!
@IBOutlet weak var inspiredButton: UIButton!

I have created an object of the storyviewcontroller class and am able to access its variables. However, after creating the object of the storyviewcontroller, the IBOutlet is nil. Because of this, I get an exception saying found nil while unwrapping

let story:StoryViewController = StoryViewController()
story.textLabel.text = sampleText()

Can you please help me with this! Here is a link to the whole project https://github.com/abhishekagarwal2301/DTC Thanks


Solution

  • IBOutlets are initialized during view loading process and they are not accessible at the point you are trying to reach them. Instead you must declare a string variable to your viewcontroller and set text to label on its viewDidLoad method (after the loading process has finished)

    class StoryViewController: UIViewController {
        @IBOutlet weak var textLabel: UILabel!
        @IBOutlet weak var inspiredButton: UIButton!
        var text:String!
    
       override func viewDidLoad() {
        super.viewDidLoad()
    
        textLabel.text = text
       }
    }
    

    And from first controller initialize text variable as follow

    let storyboard = UIStoryboard(name: "YourStoryboardName", bundle: nil)
    var story = storyboard.instantiateViewControllerWithIdentifier("YourVCIdentifier") as StoryViewController
    story.text = sampleText()
    self.presentViewController(story, animated: false , completion: nil)