如何使用swift 4的图像数组在UICollectionViewCell中制作翻转动画

时间:2018-06-17 14:35:54

标签: swift xcode animation uicollectionview uicollectionviewcell

我试图在UICollectionViewCell中实现翻转动画。我用2种类型的图像完成了它。但我不知道如何在图像阵列中实现它。现在的逻辑: enter image description here

但我想要这样的逻辑: enter image description here

这是我的代码:

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

请帮我实现这个逻辑!非常感谢!!

0 个答案:

没有答案