簡體   English   中英

Swift OSX-從另一個類甚至線程更新NSTextView

[英]Swift OSX - update NSTextView from another class and maybe thread

我是Swift編程的新手,我的背景一直是過程語言,因此對語言和一些OO概念都非常滿意。

我正在構建一個OSX應用程序,該應用程序具有1個GUI窗口,2個輸入字段和一個按鈕-單擊該按鈕時,程序將從在1個文本框中輸入的文件夾中獲取圖像文件,並將其復制到在1個文本框中輸入的文件夾中。第二個文本框。 在這個主窗口上,我們使用NSTextView作為輸出日志,以便用戶知道復制的進度。

ViewController.swift 
utilities.swift
ImageCopy.swift

這3個控件在我的ViewController中定義

@IBOutlet var logView: NSTextView!
@IBOutlet weak var sourceFolder: NSTextField!
@IBOutlet weak var targetFolder: NSTextField!

按鈕代碼為:

@IBAction func ExecuteButtonPressed(_ sender: NSButtonCell){
    utilities.writeToLog(lineOfText: "Copy process starting\n")
    processImages(inputFolder, outputFolder) // <-- This can take some time
utilities.writeToLog(lineOfText: "Copy process ended\n")
} 

在utilities.swift中,writeToLog函數定義為:

class utilities{
    static func writeToLog(lineOfText: String){

    // Get current viewcontroller where the logview textview is
    let vc = (NSApplication.shared.keyWindow?.contentViewController as! ViewController)

    let calendar = Calendar.current
    let time=calendar.dateComponents([.hour,.minute,.second], from: Date())

    let outputLineOfText = "\(time.hour!):\(time.minute!):\(time.second!) - " + lineOfText

    vc.logView.textStorage?.append(NSAttributedString(string: outputLineOfText))
    vc.logView.scrollToEndOfDocument(self)

}

所有復制功能都在ImageCopy.swift文件中,並利用writeToLog()函數嘗試在進度進行時寫入GUI控件。

該應用程序都工作在一個例外情況下-由於ProcessImages()函數可能會花費很長時間,並且據我所知,該函數正在主線程上運行,因此它將阻止GUI更新,因此一旦ProcessImages()函數返回logView NSTextView更新,一次全部。

我想我需要在線程上運行ProcessImages()函數,但是當我這樣做時,它仍然沒有更新logView。

任何幫助將非常感激。

******************************************更新

我想我現在走對了。 我正在調查委托和通知,以便在后台線程和UI視圖之間進行通信。

******************************************更新

我想我現在走對了。 我正在調查委托和通知,以便在后台線程和UI視圖之間進行通信。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM