Search code examples
swiftswift3swift-playground

Playground, unable to set same UIImageView to more than one UIView


I've got this code

    override public func viewDidLoad() {

    let imageBlankCard = UIImage(named: "BlankCard.png")
    let imageViewBlankCard = UIImageView(image: imageBlankCard)

    rockCard.addSubview(imageViewBlankCard)
    scissorCard.addSubview(imageViewBlankCard)
    paperCard.addSubview(imageViewBlankCard)

    self.view.addSubview(rockCard)
    self.view.addSubview(scissorCard)
    self.view.addSubview(paperCard)

}

But when I run the playground, only the latest UIView (paperCard) is displayed properly, the other cards are not shown at all as you can see in the image here: there should be two cards like the last one, in place of the arrows. Can someone help me? Thanks everybody!


Solution

  • According to the documentation,

    Views can have only one superview. If view already has a superview and that view is not the receiver, this method removes the previous superview before making the receiver its new superview.

    This explains the behaviour that you're getting.

    One solution to this is to create three separate image views and add each of them as a subview.

    Judging by the variable names, I think you are creating something similar to a rock paper scissors game. And you have three views that each holds an image view with the image of a blank card. And you want to add the image of a stone, paper and scissors as an overlay to the image view. If that's what you want to do, why not just make rockCard, paperCard and scissorsCard themselves UIImageViews and set the image to be BalnkCard.png?

    let imageBlankCard = UIImage(named: "BlankCard.png")
    rockCard.image = imageBlankCard
    scissorsCard.image = imageBlankCard
    paperCard.image = imageBlankCard