user11535633
user11535633

Reputation:

How can I solve "Cannot assign value of type 'UIImageView?' to type 'UIImage?'" issue?

Disclaimer: I have modified/am modifying a project my tutor downloaded off the internet.

This is my homework project: 3 fortune cookies on the screen, user hits "Find out my fortune" button, which selects one of the three cookies at random (using the .randomElement() property). A window opens, displaying that random cookie image. However, I am unable to set the image within the window to the result of the .randomElement() property

I have already tried trying to convert the UIImage to UIImageView and vice versa, but now am at my wits end.

Here is the global class of the random element being formed

class globalElements {
    static let cookiesArray = [globalElements.numberOne,        
        globalElements.numberTwo, globalElements.numberThree]
    static let randomlyAssignedCookie = cookiesArray.randomElement()

}


//And here is where the title error shows up:


let randomlyChosenFortune: UIImageView = {
    let image = UIImageView()
    image.translatesAutoresizingMaskIntoConstraints = false
    image.clipsToBounds = true
    image.contentMode = .scaleAspectFit
    image.image = globalElements.randomlyAssignedCookie //(error: Cannot assign value of type 'UIImageView?' to type 'UIImage?')//

    return image
}()

Upvotes: 0

Views: 2334

Answers (2)

David Chopin
David Chopin

Reputation: 3064

You are trying to assign a UIImageView to the type UIImage. These are two different things. For starters, I would name "image" when assigning randomlyChosenFortune to "imageView." UIImageView is a subclass of UIView, i.e. it can be added to a view hierarchy. UIImage is simply an image. It doesn't have things like frames, corner radii, border widths, etc.

This means that, when you want to actually add a UIImage that you've created in code to your views, you need to do so by:

  1. Creating an instance of UIImageView
  2. Setting that UIImageView's optional image property to a UIImage
  3. Add the UIImageView to your view hierarchy

Here's a good reference for you to learn up on the differences: Difference between UIImage and UIImageView

UIImage reference: https://developer.apple.com/documentation/uikit/uiimage

UIImageView reference: https://developer.apple.com/documentation/uikit/uiimageview

Understanding UIView subclassing: https://developer.apple.com/documentation/uikit/uiview & https://medium.com/@fvaldivia/view-hierarchy-in-swift-ios-9f86a7479cb5

Upvotes: 1

emrcftci
emrcftci

Reputation: 3514

You should set UIImage to UIImageView's UIImage.

Probably your globalElements.randomlyAssignedCookietype is not a UIImage.

If you want to set image to UIImageView you should use UIImage type.

Only the same types can be synchronized to each other

I hope this makes the difference.

Enjoy.

Upvotes: 1

Related Questions