gpt4 book ai didi

swift - 如何防止按钮在每次点击时反复运行?

转载 作者:行者123 更新时间:2023-11-30 12:56:55 25 4
gpt4 key购买 nike

我不知道为什么,但我假设按钮不应该可以一次又一次地点击来重做自己......

我有一个相当简单的代码。当我的按钮被点击时,它使用 urlSession 将图像下载到另一个 viewController 的背景 View 中并继续进入其中。

我的问题是,如果在等待图像加载时单击按钮 3 次,我的 viewController 将向下 3 层进入导航 Controller ,并且要返回到原始 viewController,我必须单击后退按钮 3 次。我不是应该不能往下连续3层吗!?

@IBAction func showImage(_: UIButton) {

loadImage()
}
func loadImage () {
let url = URL(string: "https://upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/1280px-Flag_of_the_United_States.svg.png")
var request = NSMutableURLRequest(url: url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
request.httpMethod = "GET"
let session = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
guard let data = data else {
print("You got an error:\(error)")
return
}
let img = UIImage(data: data )
let imgview = UIImageView(image: img)
let sb = UIStoryboard(name: "Main", bundle: nil)
let ivc = sb.instantiateViewController(withIdentifier: "showImage")
ivc.view = imgview
self.navigationController?.pushViewController(ivc, animated: true)
}
session.resume()
}

最佳答案

感谢 Phillip Mills 的评论,这就是我所做的:

我添加了

@IBOutlet weak var showImage: UIButton!

然后点击后,我禁用了该按钮:

showImage.isEnabled = false

完成转场后,我再次启用它:

showImage.isEnabled = true

我的完整代码是:

@IBOutlet weak var showImage: UIButton!  // Added
@IBAction func showImage(_: UIButton) {
showImage.isEnabled = false // Added
loadImage()
}
func loadImage () {
let url = URL(string: "https://upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/1280px-Flag_of_the_United_States.svg.png")
var request = NSMutableURLRequest(url: url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
request.httpMethod = "GET"
let session = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
guard let data = data else {
print("You got an error:\(error)")
return
}
let img = UIImage(data: data )
let imgview = UIImageView(image: img)
let sb = UIStoryboard(name: "Main", bundle: nil)
let ivc = sb.instantiateViewController(withIdentifier: "showImage")
ivc.view = imgview
self.navigationController?.pushViewController(ivc, animated: true)
self.showImage.isEnabled = true // Added


}
session.resume()
}

关于swift - 如何防止按钮在每次点击时反复运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40312341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com