首页 > 解决方案 > 如何在 UICollectionViewCell 中使用图像数组 swift 4 制作翻转动画

问题描述

我正在尝试在 UICollectionViewCell 中实现翻转动画。我用两种类型的图像完成了它。但我不知道如何在图像数组中实现它。现在的逻辑: 在此处输入图像描述

但我想要这样的逻辑: 在此处输入图像描述

这是我的代码:

 import UIKit

    class CollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var coImage: UIImageView!

    let cardBackTag = 0
    let cardFrontTag = 1

    var cardViews: (frontView: UIImageView, backView: UIImageView)?

    var imgViewFront: UIImageView!
    var imgViewBack: UIImageView!

    override func awakeFromNib() {
        super.awakeFromNib()
        imgViewFront = self.createCardWithImage(imageName: "1", tag: self.cardFrontTag)
        imgViewBack = self.createCardWithImage(imageName: "2", tag: self.cardBackTag)
        cardViews = (frontView: imgViewFront, backView: imgViewBack)
        contentView.addSubview(imgViewBack)
    }
    private func createCardWithImage(imageName: String, tag: Int) -> UIImageView {
        let newCardImageView = UIImageView(frame: self.frame)
        newCardImageView.image = UIImage(named: imageName)
        newCardImageView.tag = tag

        return newCardImageView
    }

    func flipCardAnimation(indexPath: IndexPath) {

        if (imgViewBack.superview != nil) {
            cardViews = (frontView: imgViewFront, backView: imgViewBack)
        }else{
            cardViews = (frontView: imgViewBack, backView: imgViewFront)
        }

        let transitionOptions = UIViewAnimationOptions.transitionFlipFromLeft

        UIView.transition(with: self.contentView, duration: 1.0, options: transitionOptions, animations: {

            self.cardViews!.backView.removeFromSuperview()

            self.contentView.addSubview(self.cardViews!.frontView)

        }, completion: { finished in
            print(indexPath)
        })
    }
}

import UIKit


class CollectionViewController: UICollectionViewController {

    var reuseIdentifier = "CollectionViewCell"

    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView!.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
    }

    // MARK: UICollectionViewDataSource

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return 8
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell

        return cell
    }

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as! CollectionViewCell

        cell.flipCardAnimation(indexPath: indexPath)
    }
}

请帮我实现这个逻辑!十分感谢!!

标签: swiftxcodeanimationuicollectionviewuicollectionviewcell

解决方案


推荐阅读