Justin Frazer
Justin Frazer

Reputation: 970

ImageView retuning nil

I have a view controller OtherUserAccountViewController containing a button with a "profile picture" as its background. When this button is tapped, I would like to push a new view controller ImageTappedViewController onto the stack to simply present a bigger ImageView of this said profile picture. Please note the Storyboard identifier for the screenshot seen below is in fact "imageTapped" and the class is ImageTappedViewController

Below is my function for instantiating and pushing the new view controller:

In OtherUserAccountViewController.swift:

@IBAction func profilePicButtonTapped() {

    let sb = UIStoryboard(name: "SuccessfulLogin", bundle: nil) //SB name: SuccessfulLogin

    let cc = (sb.instantiateViewController(withIdentifier: "imageTapped")) as!  ImageTappedViewController

    if cc.imageView == nil || cc.imageView == UIImage() {
        print("Nil") //<- Nil is printed upon firing this function
    } else {
        print("not nil")
    }

    //cc.imageView.image = self.profilePicButton.currentBackgroundImage <- breaks because the imageView is nil

    self.navigationController?.pushViewController(cc, animated: true)
}

ImageTappedViewController.swift:

import UIKit

class ImageTappedViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
}

I am totally lost as to why this imageView is returning nil.

I set the imageView to display the lovely Taylor Swift on default as seen below; but regardless, nil is being returned.

ImageTappedViewController

Any help is much appreciated!

Upvotes: 0

Views: 922

Answers (1)

beyowulf
beyowulf

Reputation: 15331

When view controllers are first initialized their IBOutlets will not be initialized. Only after viewDidLoad will all of their outlets be non-nil. Pass the image as a UIImage then in viewDidLoad set image view's image property.

Upvotes: 1

Related Questions