将多个UIImage添加到具有相同名称的UIStackView中

问题描述 投票:0回答:1

我正在尝试基于变量'num'的值将图像添加到堆栈视图。每个添加的其他图像都应该是一个名为“ girl”的图像或一个名为“ boy”的图像,这两个图像均位于我的资源文件夹中。现在,ViewDidLoad正在调用updateSilhouetteView()函数在num <3的情况下,一切工作正常,但是在每个图像已经存在一个图像后,它将停止添加。swift的同名图片是否有问题?我该如何解决?

@IBOutlet weak var silhouetteStack: UIStackView!
    let boy = UIImageView(image: UIImage(named: "boy"))
    let girl = UIImageView(image: UIImage(named: "girl"))
    var silhouettes: [UIImageView] = []
    var num = 3
func updateSilhouetteView() {
        for n in 0..<num {
            if n % 2 == 0 {
                silhouettes.append(boy)
                silhouettes[n].image = UIImage(named: "boy")
                print("boy")
            } else {
                silhouettes.append(girl)
                silhouettes[n].image = UIImage(named: "girl")
                print("girl")
            }
            silhouettes[n].frame = CGRect(x: 210, y: 500, width: 205, height: 120)
            silhouettes[n].contentMode = .scaleAspectFit
            silhouetteStack.addArrangedSubview(silhouettes[n])
        }
    }
swift xcode uiimageview uiimage
1个回答
0
投票

这将创建一个新对象并按预期工作。

@IBOutlet weak var silhouetteStack: UIStackView!
//let boy = UIImageView(image: UIImage(named: "boy"))
//let girl = UIImageView(image: UIImage(named: "girl"))
var silhouettes: [UIImageView] = []
var num = 3
func updateSilhouetteView() {
    for n in 0..<num {
        if n % 2 == 0 {
            silhouettes.append(UIImageView(image: UIImage(named: "boy")))
            //silhouettes[n].image = UIImage(named: "boy")
            print("boy")
        } else {
            silhouettes.append(UIImageView(image: UIImage(named: "girl")))
            //silhouettes[n].image = UIImage(named: "girl")
            print("girl")
        }
        silhouettes[n].frame = CGRect(x: 210, y: 500, width: 205, height: 120)
        silhouettes[n].contentMode = .scaleAspectFit
        silhouetteStack.addArrangedSubview(silhouettes[n])
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.