游乐场,无法将相同的 UIImageView 设置为多个 UIView

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

我有这个代码

    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)

}

但是当我运行游乐场时,只有最新的UIView(paperCard)可以正确显示,其他卡片根本没有显示,如图所示here:应该有像上一张一样是两张牌,代替箭头。 有人能帮我吗?谢谢大家!

根据 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.

这解释了您的行为。

一个解决方案是创建三个单独的图像视图并将它们中的每一个添加为子视图。

从变量名来看,我认为您正在创建类似于剪刀石头布游戏的东西。你有三个视图,每个视图都有一个带有空白卡片图像的图像视图。并且您想将石头、布和剪刀的图像作为叠加层添加到图像视图中。如果那是你想做的,为什么不自己制作 rockCardpaperCardscissorsCard UIImageViews 并将图像设置为 BalnkCard.png?

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