简体   繁体   中英

Generate imageView based off array.count - Swift

I am trying to generate a section of image views which will sit at the top of an application and update as the user progresses through the quiz.

My array variable is Qs, the code I have to generate an imageView is as follows:

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)
}

I already have a variable which tracks the users progress through the quiz with just an integer if that would be any help, its declared along with the quiz functionality. Here is a fantastically draw visual of what I am trying to accomplish:

在此处输入图片说明

Any help is appreciated, thanks

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM