Ross Sullivan
Ross Sullivan

Reputation: 415

UIImageView image change delay when tapped

I have a UIImageView with a tap gesture recognizer. When tapped I want the UIImageView to alternate between 2 images. The code I have achieves this but when the UIImageView is tapped repeatedly very quickly the UIImageView seems to lag and get behind.

My Code:

@IBOutlet weak var moneyButton: UIImageView!

let benchUpImage = UIImage(named: "benchUp")
let benchDownImage = UIImage(named: "benchDown")
var benchIsDown = false

func moneyButtonPressed(sender: UITapGestureRecognizer){

    if benchIsDown == false{
        moneyButton.image = benchDownImage
        benchIsDown = true
    }else{
        moneyButton.image = benchUpImage
        benchIsDown = false
    }

}

Upvotes: 0

Views: 234

Answers (2)

GeneCode
GeneCode

Reputation: 7588

I think the problem with your code is that you don't handle the states of the recognizer. Thus, multiple tapping quickly make the image change at every state (begin, end, etc). Try to put the changing code in state "end" only:

func moneyButtonPressed(sender: UITapGestureRecognizer){

   if sender.state == .Ended {
    if benchIsDown == false{
        moneyButton.image = benchDownImage
        benchIsDown = true
    }else{
        moneyButton.image = benchUpImage
        benchIsDown = false
    }
   }

}

Upvotes: 0

Vikky
Vikky

Reputation: 936

Swift 3.0

You can simply allow user to tap with some delay. Consider replacing your code by below one

var canUserTap = true
let delayTime = 0.4 //setDelayTimming in seconds
@IBAction func moneyButtonPressed( _ sender : UITapGestureRecognizer){
    if(canUserTap){
        if benchIsDown == false{
            moneyButton.image = benchDownImage
            benchIsDown = true
        }else{
            moneyButton.image = benchUpImage
            benchIsDown = false
        }
        canUserTap = false
        Timer.scheduledTimer(timeInterval: delayTime,
                             target:self,
                             selector:#selector(allowUserTap(_:)),
                             userInfo:nil,
                             repeats:false)
    }

}

func allowUserTap(_ timer:Timer){
    canUserTap = true

}

Upvotes: 0

Related Questions