点击时UIImageView图像更改延迟

时间:2017-07-26 23:35:05

标签: ios swift uiimageview uitapgesturerecognizer

我有一个带有轻敲手势识别器的UIImageView。点击时我希望UIImageView在2张图像之间切换。我已经实现了这个代码,但是当UIImageView被反复轻敲时,UIImageView似乎滞后并落后。

我的代码:

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

}

2 个答案:

答案 0 :(得分:0)

Swift 3.0

您可以简单地允许用户点按一些延迟。考虑用下面的代码替换你的代码

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

}

答案 1 :(得分:0)

我认为你的代码存在的问题是你没有处理识别器的状态。因此,多次敲击可快速使图像在每个状态(开始,结束等)发生变化。尝试将更改的代码仅置于“结束”状态:

func moneyButtonPressed(sender: UITapGestureRecognizer){

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

}