Вместо 5 рандомных картинок выводится одна

введите сюда описание изображения

Мне нужно отобразить пять рандомных картинок в стеке, но выводится одна, подскажите в чем дело, пожалуйста

Вот код:

import UIKit
import SnapKit

class ViewController: UIViewController {
    
    private lazy var stackView: UIStackView = {
        let view = UIStackView()
        view.axis = .vertical
        view.distribution = .fillEqually
        view.spacing = 10
        return view
    }()
    
    private lazy var imageView: UIImageView = {
        let view = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
        view.contentMode = .scaleAspectFit
//        view.image = image
        return view
    }()
    
    private lazy var service = Service()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(imageView)
        view.addSubview(activityIndicator)
        activityIndicator.startAnimating()
        
        
        
        onLoad()
        setupViews()
    }
    
    private func setupViews() {
        view.addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottomMargin)
            make.top.equalTo(view.safeAreaLayoutGuide.snp.topMargin)
            make.left.right.equalToSuperview()
        }
        stackView.addArrangedSubview(activityIndicator)
    }
    
    private lazy var activityIndicator: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(frame: CGRect(x: 220, y: 220, width: 140, height: 140))
        view.style = .large
        return view
    }()
    
    var images: [UIImage] = []
    
    private func onLoad() {
        let dispatchGroup = DispatchGroup()
        
        for _ in 0...4 {
            dispatchGroup.enter()
            
            self.service.getImageURL { url, error in
                guard let url = url
                else { return }
                let image = self.service.loadImage(urlString: url)
                
                if let image = image {
                    self.images.append(image)
                    print(self.images.count)
                }
                dispatchGroup.leave()
            }
        }
        dispatchGroup.notify(queue: DispatchQueue.main) { [weak self] in
            guard let self = self else { return }
            self.activityIndicator.stopAnimating()
            
            for i in 0...4 {
                self.imageView.image = self.images[i]
                self.stackView.addArrangedSubview(self.imageView)
                
            }
        }
    }
    
}
import UIKit

struct Service {
    
    func loadImage(urlString: String) -> UIImage? {
        guard
            let url = URL(string: urlString),
            let data = try? Data(contentsOf: url)
        else {
            print("Ошибка, не удалось загрузить изображение")
            return nil
        }
        
        return UIImage(data: data)
    }
    
    func getImageURL(completion: @escaping (String?, Error?) -> Void) {
        let url = URL(string: "https://dog.ceo/api/breeds/image/random")
        let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
            guard let data = data else {
                completion(nil, error)
                return
            }
            let someDictionaryFromJSON = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]
            let imageUrl = someDictionaryFromJSON?["message"] as? String
            completion(imageUrl, error)
        }
        task.resume()
    }
}

Нужно сделать именно через DispatchGroup


Ответы (1 шт):

Автор решения: schmidt9

self.stackView.addArrangedSubview(self.imageView) - здесь self.imageView будет добавлено только один раз, повторно добавление не делается

The stack view ensures that the arrangedSubviews array is always a subset of its subviews array. This method automatically adds the provided view as a subview of the stack view, if it isn’t already. If the view is already a subview, this operation doesn’t alter the subview ordering.

для исправления создавайте экземпляры заново

for i in 0...4 {
   let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
   imageView.contentMode = .scaleAspectFit
                
   imageView.image = self.images[i]
   self.stackView.addArrangedSubview(imageView)
}
→ Ссылка