如何对 UIImages 数组进行排序?

How to sort array of UIImages?

我有3张图片,我需要用动画实现它们。我如何使用循环在屏幕上单独显示每个图像?请帮助我

class ViewController: UIViewController {
    var imageArray: [UIImage] = [UIImage(named: "1")!, UIImage(named: "2")!, UIImage(named: "3")!]
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(handleTimer), userInfo: nil, repeats: false)
    }
    
    private func setImageSettings(to image: UIImage?) -> UIImageView {
        let pictureParams = UIImageView(image: image)
        pictureParams.frame.size = CGSize(width: 400, height: 300)
        pictureParams.center = view.center
        pictureParams.contentMode = .scaleAspectFit
        view.addSubview(pictureParams)
        return pictureParams
    } 
    func moveImages(_ targetView: UIImageView) {
        UIImageView.animate(withDuration: 2, delay: 0, options: [], animations: {targetView.frame.origin = CGPoint(x: targetView.frame.origin.x + 320, y: targetView.frame.origin.y )}, completion: nil)
    }   
    func sortImages() {
        for image in imageArray{
            moveImages(setImageSettings(to: image))
        }
    }
    @objc private func handleTimer(_ sender: Timer) {
        sortImages()
    }
}

假设您希望一次为一张图像制作动画,出现在视图控制器视图的中间,然后向上移动到视图的顶部,您可以像这样更改代码:

class ViewController: UIViewController {
    var imageIndex = 0
    var imageArray: [UIImage] = [UIImage(named: "1")!, UIImage(named: "2")!, UIImage(named: "3")!]
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        let timer: Timer? = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(handleTimer), userInfo: nil, repeats: true)
    }
    
    private func setImageSettings(to image: UIImage?) -> UIImageView {
        let pictureParams = UIImageView(image: image)
        pictureParams.frame.size = CGSize(width: 400, height: 300)
        pictureParams.center = view.center
        pictureParams.contentMode = .scaleAspectFit
        view.addSubview(pictureParams)
        return pictureParams
    } 

    func moveImages(_ targetView: UIImageView) {
        UIImageView.animate(withDuration: 2, delay: 0, options: [], animations: {targetView.frame.origin = CGPoint(x: targetView.frame.origin.x + 320, y: targetView.frame.origin.y )}, completion: nil)
    }   

    func animateImages() {
        // Fetch an image from the array
        let image = imageArray[imageIndex]

        // Create the animation for that image
        moveImages(setImageSettings(to: image))

        // Move on to the next image index
        imageIndex += 1

        // If we are past the end of the array, stop.
        if imageIndex == imagesArray.count {
            timer.invalidate() 
        }
    }

    @objc private func handleTimer(_ sender: Timer) {
        animateImages()
    }
}