简体   繁体   中英

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
    }

}

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

}

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM