当用户单击按钮然后迅速恢复到原始图像时,如何使图像改变几秒钟?

时间:2019-05-11 17:35:56

标签: swift

嗨,我是Swift编码的新手,而且我对Stackoverflow也很陌生。我该如何制作一个按钮来更改图像约5秒钟,然后在用户点击按钮时返回到原始图像?

我尝试使用此代码


       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), {
           gauntletImage.image = UIImage(named: gauntlet["gauntlet2"]) //change back to the old image after 5 sec
       });

但是我仍然收到这两个错误:

无法将类型“ Int”的值转换为预期的参数类型“ dispatch_time_t”(也称为“ UInt64”)

歧义使用'dispatch_get_main_queue()'

这是我正在使用的更多代码。

@IBOutlet weak var gauntletImage: UIImageView!

    let gauntlet = ["gauntlet1", "gauntlet2", "gauntlet3", "gauntlet4", "gauntlet5", "gauntlet6",]


    @IBAction func stonePressed(_ sender: UIButton) {
        print(sender.tag)

        gauntletImage.image = UIImage(named: gauntlet[sender.tag - 1]) //change to the new image

        dispatch_after(dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), (Int64)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), {
            gauntletImage.image = UIImage(named: gauntlet["gauntlet2"]) //change back to the old image after 5 sec
        });
    }

1 个答案:

答案 0 :(得分:2)

您可以尝试

@IBAction func stonePressed(_ sender: UIButton) { 
    // store old image assuming it has an initial image in storyboard
    let oldImg = gauntletImage.image!
    // set new image
    gauntletImage.image = UIImage(named: gauntlet[sender.tag - 1])  
    // wait 5 seconds 
    DispatchQueue.main.asyncAfter(deadline: .now() + 5 ) { 
        // set back old image
        self.gauntletImage.image = oldImg   
   }   

}

用户可以多次单击它,因此您可以这样做

sender.isEnabled = false

在存储旧图像并将其设置为块之后的分派中将其重新设置为true