I'm trying to add images to a stack view based on the value of the variable 'num'. Every odd image should be an image called "girl" and even an image called "boy", both of which reside in my assets folder. Right now the updateSilhouetteView() function is being called by ViewDidLoad. Everything works perfectly for num < 3, but it stops adding them after there is already one of each image. Does swift have a problem with images of the same name? How can I get around this?
@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])
}
}
This should create a new object for each UIImageView and work as expected. Basically, I am creating a new instance of UIImageView and then adding it to the array. You were adding the same instance, again and again. As a result, the stack view is getting a reference to only 2 distinct UIImageView instances.
@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 viewDidLoad() {
silhouetteStack.distribution = .fillEqually
}
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])
}
}