在Swift 4.0 Cocoa应用程序中,可以通过以下步骤将标准输出重定向到NSScrollView:
availableData
方法来获取输出数据,并将其发送到一个通知中心。import Foundation
class OutputHandler: FileHandle {
override func availableData() -> Data {
let data = super.availableData()
NotificationCenter.default.post(name: NSNotification.Name("OutputDataNotification"), object: data)
return data
}
}
let pipe = Pipe()
let outputHandler = OutputHandler(fileDescriptor: pipe.fileHandleForReading.fileDescriptor)
FileHandle.standardOutput = outputHandler
let scrollView = NSScrollView()
scrollView.hasVerticalScroller = true
scrollView.autoresizingMask = [.width, .height]
let textView = NSTextView()
textView.isEditable = false
textView.isSelectable = true
textView.autoresizingMask = .width
scrollView.documentView = textView
// 添加scrollView到视图层次结构中
NotificationCenter.default.addObserver(forName: NSNotification.Name("OutputDataNotification"), object: nil, queue: nil) { notification in
if let data = notification.object as? Data, let outputString = String(data: data, encoding: .utf8) {
DispatchQueue.main.async {
textView.string += outputString
textView.scrollToEndOfDocument(nil)
}
}
}
通过以上步骤,标准输出的数据将被捕获并显示在NSScrollView中。这在调试和记录应用程序输出时非常有用。
推荐的腾讯云相关产品:腾讯云服务器(CVM),产品介绍链接地址:https://cloud.tencent.com/product/cvm
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云