我不知道为什么我不能在我的 UILabel 中打印我的“pocetDatabaze3”。
这是我的代码:
@IBOutlet weak var aktualniPocet: UILabel!
var pocetDatabaze2 = 0
var pocetDatabaze3 = "dfh"
override func viewDidLoad() {
super.viewDidLoad()
if let url = NSURL(string: "http://servis.dronysitmp.cz/cteni_baterie.php") {
let task = URLSession.shared.dataTask(with: url as URL, completionHandler: { (data, response, error) -> Void in
//print(data)
if let pocetDatabaze = NSString(data: data!, encoding: String.Encoding.ascii.rawValue){
self.pocetDatabaze2 = Int(pocetDatabaze as String)!
//self.pocetDatabaze3 = String(describing: pocetDatabaze)
}
}
);
task.resume()
}
pocetDatabaze3 = String(pocetDatabaze2 as Int)
aktualniPocet.text = pocetDatabaze3
}
在 UILabel 中,它显示“0”,但应该是“25”。加载此 View 后,我还有两个操作。当我使用它们时,它会显示正确的值。剩下的就是:
@IBAction func odecteni(_ sender: UIButton) {
pocetDatabaze2 = pocetDatabaze2 - 1
self.pocetDatabaze3 = String(pocetDatabaze2 as Int)
aktualniPocet.text = pocetDatabaze3
}
Best Answer-推荐答案 strong>
这是一个线程问题。 URLSession 是异步的,所以你必须在 completionHandler 中更新 UI。
let task = URLSession.shared.dataTask(with: url as URL, completionHandler: { (data, response, error) -> Void in
//print(data)
if let pocetDatabaze = NSString(data: data!, encoding: String.Encoding.ascii.rawValue) {
self.pocetDatabaze2 = Int(pocetDatabaze as String)!
self.pocetDatabaze3 = String(pocetDatabaze2 as Int)
DispatchQueue.main.async {
self.aktualniPocet.text = pocetDatabaze3
}
}
})
您需要调用 DispatchQueue.main ,因为您应该在主线程中更新 UI。然后你可以注释掉另外两个调用。
关于ios - 无法在 UILabel 中显示我的文本,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/46075650/
|