首页 > 解决方案 > 基于 array.count 生成 imageView - Swift

问题描述

我正在尝试生成一部分图像视图,它将位于应用程序的顶部并随着用户进行测验而更新。

我的数组变量是Qs,生成imageView的代码如下:

var imageView: UIImageView!
var i = 0
var total = Int(Qs.capacity) // Just testing what .capacity does.

for i in 0..<(Qs.count-1){
imageView - UIImageView(frame: CGRect(x: 0, y: 75, width: 50, height: 50))
imageView.image = UIImage(named:"InfoIcon")
imageView.contentMode = .scaleAspectFit

self.view.addSubView(imageView)
}

我已经有一个变量来跟踪用户在测验中的进度,如果这有帮助的话,它会与测验功能一起声明。这是我要完成的工作的奇妙视觉效果:

在此处输入图像描述

任何帮助表示赞赏,谢谢

标签: arraysswiftloopsfor-loopimageview

解决方案


Lets assume you have a container view attached at the top, then you can use this method to add any number of imageView's.

func addProgressImages(to view: UIView, count: Int) {
    let screenSize = UIScreen.main.bounds.size

    for i in 0..<count {
        let spacing: CGFloat = 2
        let tag = i + 888
        let width: CGFloat = screenSize.width/CGFloat(count)
        let height: CGFloat = width
        if let view = view.viewWithTag(tag) {
            view.removeFromSuperview()
        }
        let x = spacing + CGFloat(i) * width
        let imageView = UIImageView(frame: CGRect(x: x, y: 100, width: width - spacing, height: height))
        imageView.image = UIImage(named:"InfoIcon")
        imageView.tag = tag
        imageView.contentMode = .scaleAspectFit
        view.addSubview(imageView)
    }
} 

You can play with y value for vertical alignment.


推荐阅读