swift - 如何在用户单击按钮时使图像更改几秒钟,然后 swift 恢复为原始图像?

标签 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
        });
    }

最佳答案

你可以试试

@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 block 后调度

关于swift - 如何在用户单击按钮时使图像更改几秒钟,然后 swift 恢复为原始图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56092764/

相关文章:

Swift if/else 语句 Sprite Kit

ios - "Fatal error"崩溃于 "if let"

swift - 如何在通用协议(protocol)上使用 if-let?

ios - UIAlertController 默认首字母大写

c - 如何在框架中使用 Swift 文件中的 C dylib

Swift:反射(reflect) NSManagedObject 子类的属性

ios - 以编程方式添加 CenterX/CenterY 约束

swift - 如何在 spritekit 中创建垂直滚动菜单?

ios - 如何使用@objc 标签传递 swift 枚举

swift - CIFeature 没有成员 hasLeftEyePosition