Search code examples
iosswiftxcodeuiimageviewuikit

How to allow only one UIImageView to be touched at a time


I have built a simple memory game which consists of 16 UIImageViews.
board with no flipped cards

For the memory game, you are only supposed to be able to touch one card at a time. When you touch the card, it flips over and reveals the image underneath

board with one flipped card

My issue is that I only want the user to be able to touch one image view at a time. When a user taps on two cards at the same time, it glitches the game. So my question is how do I allow only 1 UIImageView to perform an action at a time, and not allow multiple UIImageViews to perform an action at the same time if touched simultaneously.


Solution

  • Assuming that the user has to unflip a card by selecting it again, I would suggest adding a property to your viewController to keep track of the selectedCard. If there is already a selected card, ignore all others.

    var selectedCard: UIImageView?
    
    @objc func handleTap(_ recognizer: UITapGestureRecognizer) {
        guard let imageView = recognizer.view as? UIImageView else { return }
        if let selected = selectedCard {
            if selected === imageView {
                // unflip the card
                imageView.image = backOfCard
                selectedCard = nil
            }
        } else {
            // display face of card
            imageView.image = ...
            selectedCard = imageView
        }
    }
    

    Note: Even if a user taps two cards at the same time, handleTap will be called twice in succession. The first card will win and be flipped and become the selectedCard and the second card will be ignored because the if selected === imageView test will fail.