如何以编程方式添加多个UIImageView?

时间:2017-10-11 17:39:17

标签: arrays swift image

我努力让所有优惠券(UIImage)出现。例如,我有3张优惠券,当我运行我的代码时,它会一直显示第3张优惠券的图像。怎么没有显示前两个?提前谢谢。

  override func viewDidLoad() {
    var i: Int = 0
    super.viewDidLoad()
    self.view.backgroundColor = UIColor.white

    CouponsViewController.PopulateDataCoupons()

    i=0
    repeat {
            let imageName = MyCoupons.siteCoupons[i]//"Coupons1.jpg"
            let image = UIImage(named: imageName!)
            let imageView = UIImageView(image: image!)
            imageView.frame = CGRect(x: 50, y: 50, width: 350, height: 300)
            view.addSubview(imageView)
            i += 1 }
    while (i < MyCoupons.count-1)
}

1 个答案:

答案 0 :(得分:0)

您将每个UIImageView对象放在同一位置。看看这一行:

imageView.frame = CGRect(x: 50, y: 50, width: 350, height: 300)

尝试更改每次迭代的xy坐标以查看每个图片,如下所示:

let height = 350
i = 0
repeat {
        let imageName = MyCoupons.siteCoupons[i]//"Coupons1.jpg"
        let image = UIImage(named: imageName!)
        let imageView = UIImageView(image: image!)
        imageView.frame = CGRect(x: 50, y: i * height, width: 350, height: height)
        view.addSubview(imageView)
        i += 1 
}
while (i < MyCoupons.count - 1)

<强>更新

正如@Mick MacCallum指出的那样。您应该考虑UIImageView的高度。请参阅上面的更改。