Swift OSX - 从另一个类和线程更新NSTextView

时间:2018-05-22 00:52:29

标签: swift multithreading user-interface

我是Swift编程的新手,我的背景一直是程序语言,所以我要接受语言和一些OO概念。

我正在构建一个具有1个GUI窗口的OSX应用程序,其中包含2个输入字段和一个按钮 - 当单击该按钮时,程序将从其中一个文本框中输入的文件夹中获取图像文件并将其复制到在第二个文本框中输入的文件夹。在这个主窗口中,我们使用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视图之间进行通信。

1 个答案:

答案 0 :(得分:0)

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

我想我现在正走在正确的道路上。我正在调查委托和通知,以便在后台线程和UI视图之间进行通信。