[英]Label and ProgressBar doesn't update macOS Swift
我今天的代码有问题。 我尝试在for循环中更新标签和进度视图,但标签或进度条均未更新。
我不明白为什么...这是代码,如果您可以处理的话
func parseMessage()
{
var i = 0
self.beginHTML()
for row in (try? db?.prepare("SELECT message.text, message.is_from_me, datetime(substr(message.date, 1, 9) + 978307200, 'unixepoch', 'localtime') as f_date, message.cache_has_attachments, message.ROWID FROM message LEFT JOIN chat WHERE chat.guid LIKE '%PHONENUMBER%' AND chat.ROWID == message.handle_id"))!!
{
html += """
<div class=\"clear\"></div>
<p align=\"center\"> \(String(describing: row[2] ?? "")) </p>
"""
if (row[3] as! Int64 == 1)
{
self.parseAttachments(row: row)
}
else if (row[1] as! Int64 == 1)
{
html += "<div class=\"from-me\"> <p>\(String(describing: row[0] ?? "")) </p></div>"
}
else
{
html += "<div class=\"from-them\"> <p>\(String(describing: row[0] ?? "")) </p></div>"
}
i = i + 1
if (i % 500 == 0)
{
self.progressLabel.stringValue = "\(i) on \(self.messageNumber)"
self.progressBar.increment(by: 500)
// DispatchQueue.main.async {
// self.progressLabel.stringValue = "\(i) on \(self.messageNumber)"
// self.progressBar.increment(by: 500)
// }
}
if (i == 2000)
{
break;
}
}
html += "</section></body></html>"
}
我的整个代码在这里: https : //github.com/ExPl0siF/iOSMessageExport/blob/master/MessageGenerator/ViewController.swift
您不能在主线程上运行for循环并显示UI更新。 在您的代码返回并且应用程序服务主事件循环之前,不会进行UI更改。
相反,如果您发布的代码在后台线程上运行(可能应该在后台线程上运行),那么您需要在对DispatchQueue.main.async()
调用中包装UI更新(对标签和进度条的更改DispatchQueue.main.async()
func parseMessage()
{
DispatchQueue.global().async {
var i = 0
self.beginHTML()
for row in (try? db?.prepare("SELECT message.text, message.is_from_me, datetime(substr(message.date, 1, 9) + 978307200, 'unixepoch', 'localtime') as f_date, message.cache_has_attachments, message.ROWID FROM message LEFT JOIN chat WHERE chat.guid LIKE '%PHONENUMBER%' AND chat.ROWID == message.handle_id"))!!
{
html += """
<div class=\"clear\"></div>
<p align=\"center\"> \(String(describing: row[2] ?? "")) </p>
"""
if (row[3] as! Int64 == 1)
{
self.parseAttachments(row: row)
}
else if (row[1] as! Int64 == 1)
{
html += "<div class=\"from-me\"> <p>\(String(describing: row[0] ?? "")) </p></div>"
}
else
{
html += "<div class=\"from-them\"> <p>\(String(describing: row[0] ?? "")) </p></div>"
}
i = i + 1
if (i % 500 == 0)
{
DispatchQueue.main.async {
self.progressLabel.stringValue = "\(i) on \(self.messageNumber)"
self.progressBar.increment(by: 500)
}
}
if (i == 2000)
{
break;
}
}
html += "</section></body></html>"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.