I'm working with Swift 4 trying to flip a card (that is a UIImageView
) which is inside a UICollectionViewCell
.
I've two images and when I run the app, I can see one of them. But after the flip, what I get is a blue image instead of the second one.
Here's the code I've for the UICollectionViewCell
class.
import UIKit
class CardViewCell: UICollectionViewCell {
var cardFlipped = false
var frontImage = UIImage(named: "image1")
var backImage = UIImage(named: "image2")
@IBOutlet var weak cardImage: UIImageView!
@IBOutlet weak var flipCardButton: UIButton!
@IBAction func flipCardAction(_ sender: Any) {
flipCardAnimation()
}
func flipCardAnimation() {
cardFlipped ? showFront() : showBack()
contentView.reloadInputViews()
}
func showFront() {
var image = cardImage.image
image = frontImage
flipCardButton.setImage(image, for: .normal)
let transitionOptions = UIViewAnimationOptions.transitionFlipFromLeft
UIView.transition(with: flipCardButton,
duration: 0.3,
options: transitionOptions,
animations: nil,
completion: nil)
cardFlipped = true
}
func showBack() {
var image = cardImage.image
image = backImage
flipCardButton.setImage(image, for: .normal)
let transitionOptions = UIViewAnimationOptions.transitionFlipFromLeft
UIView.transition(with: flipCardButton,
duration: 0.3,
options: transitionOptions,
animations: nil,
completion: nil)
cardFlipped = false
}
}
import UIKit
private let reuseIdentifier = "CardViewCell"
class GameViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
var collectionData = ["image2", "image2", "image2", "image2", "image2", "image2", "image2", "image2", "image2", "image2", "image2", "image2", "image2", "image2", "image2", "image2"]
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
// Set up the 4x4 grid
let width = (view.frame.size.width - 60) / 4
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: width, height: width)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
collectionView.reloadData()
}
// MARK: UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return collectionData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CardViewCell
cell.cardImage.image = UIImage(named: collectionData[indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! CardViewCell
let selectedImage = collectionData[indexPath.item]
cell.flipCardAction(selectedImage)
}
}