大家好,我是 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/