我今天的代码有问题。我尝试在 for 循环内更新标签和进度 View ,但标签或进度条都没有更新。
我不明白为什么......如果你能处理的话,这是代码
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 的调用中包装 UI 更新(对标签和进度条的更改)。异步()
编辑:试试这个改变:
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>"
}
}
关于swift - Label 和 ProgressBar 不会更新 macOS Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49455636/