Home > other >  How to instantiate view controller, IBOutlets are nil when functions are called
How to instantiate view controller, IBOutlets are nil when functions are called

Time:12-08

Here is my popup view controller:

import UIKit

class PopupViewController: UIViewController {
    
    var bigVC = GameViewController()
    var cardPhoto: UIImage?
    var nameLabel: String?
    var bio: String?
    var index: Int?
    
    @IBOutlet weak var photo: UIImageView!
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var button: UIButton!
    @IBOutlet weak var story: UILabel!
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let storyboard: UIStoryboard = UIStoryboard.init(name: "Main", bundle: nil)
        let firstViewController: GameViewController = storyboard.instantiateViewController(withIdentifier: "GameScreen") as! GameViewController
        
        photo.image = cardPhoto
        label.text = nameLabel
        story.text = bio
        
        
    }
    
    
    @IBAction func removePressed(_ sender: UIButton) {
        
        bigVC.removingCard(indexToRemove: index!)
        bigVC.resetImages()
        dismiss(animated: true, completion: nil)
        
    }
    
    
}

My function bigVC.resetImages() needs to change to images of 7 buttons within an array of UIButtons. The function works perfectly but the arrays return nil and app crashes when the function is called from other view controller. How to correctly instantiate view controller so that I call these buttons?

This is popup view controller for a card game. It has a button that when pressed should remove a card from the player's hand and dismiss the popup to return back to the game view controller. How to chan

CodePudding user response:

You need to set

self.bigVC = firstViewController

then need to wait till GameViewController loaded (viewDidLoad called) before calling resetImages. So that array wont return nil.

CodePudding user response:

try this

@IBAction func removePressed(_ sender: UIButton) {
    let firstViewController = storyboard?.instantiateViewController(withIdentifier: "GameScreen") as! GameViewController
    
    firstViewController.removingCard(indexToRemove: index!)
    firstViewController.resetImages()
    dismiss(animated: true, completion: nil)
    
}
  • Related