Search code examples
iosswiftuiimageuiswipegesturerecognizer

How do I detect the name of a random UIImage?


I have a random image popping up using this code:

@IBOutlet weak var imageView: UIImageView!

@IBAction func startButton(sender: AnyObject) {

    UIView.animateWithDuration(0.5, delay:2, options:UIViewAnimationOptions.TransitionFlipFromTop, animations: {
        self.imageView.alpha = 2
        }, completion: { finished in
            self.imageView.image = UIImage(named: "gameBall\(arc4random_uniform(12) + 1).png")      
    })
}

When the user swipes down I want to detect the name of the image and then if the correct image is swiped down i want it to say "1 point!" if the wrong image is swiped down i want it to say "Game Over!" I already have some code that does not work because it only says "Game Over!" where ever I swipe:

func respondToSwipeGesture(sender: UISwipeGestureRecognizer) {
        switch sender.direction {
        case UISwipeGestureRecognizerDirection.Down:
            if imageView == UIImage(named: "gameBall2.png"){
                println("1 point!")
            }else{
                println("Game Over!")
            }
        default:
            break
        }
    }
override func viewDidLoad() {
        super.viewDidLoad()

    var swipeRight = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
    swipeRight.direction = UISwipeGestureRecognizerDirection.Right
    self.view.addGestureRecognizer(swipeRight)

    var swipeDown = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
    swipeDown.direction = UISwipeGestureRecognizerDirection.Down
    self.view.addGestureRecognizer(swipeDown)
    self.view.userInteractionEnabled = true 

Solution

  • To solve this, you may want to set the tag of the imageView.

    let randomNumber = Int(arc4random_uniform(12) + 1)
    self.imageView.image = UIImage(named: "gameBall\(randomNumber).png")
    self.imageView.tag = randomNumber
    

    Now you can compare the tag in your if condition.

    if self.imageView.tag == 2 {
        println("1 point!")
    } else {
        println("Game Over!")
    }