根据 NSPopupButton 中的选择更新 NSTextField

Update NSTextField based on selection in NSPopupButton

我只写了几个星期的代码,所以请原谅我毫无疑问的笨拙代码。

我有一个 NSTextField 需要根据 NSPopupButton

中的选择进行更新

这些是我的出口:

@IBOutlet weak var inputText: NSTextField!
@IBOutlet weak var outputText: NSTextField!
@IBOutlet weak var inputBrowseButton: NSButton!
@IBOutlet weak var outputBrowseButton: NSButton!
@IBOutlet weak var codecSelector: NSPopUpButton!

这些是我的变量:

// derive default path and filename from @IBAction of inputBrowseButton
var defaultUrl: URL! 
// derived from default of inputBrowse unless outputBrowse is used
var outputUrl: URL!
// change output path from @IBAction of outputBrowseButton
var outputDirectory: URL! 
// change path extension from @IBAction of codecSelector NSPopupButton
var codecChosen: String = "" 
// dictionary of arguments to form script for ffmpeg
var ffmpegCodecArg: String = ""

这是我将所有这些整合在一起的方法:

// construct output path for use in ffmpegArguments dictionary and display in outputText NSTextField
func updateOutputText(defaultUrl: URL?, outputDirectory: URL?) -> String {
    if defaultUrl != nil && outputDirectory != nil {
        let outputFile = defaultUrl!.deletingPathExtension()
        let outputFilename = outputFile.lastPathComponent
        outputUrl = outputDirectory!.appendingPathComponent(outputFilename)
        outputText.stringValue = outputUrl.path + "\(codecChosen)"
} else if defaultUrl == nil && outputDirectory != nil {
        outputText.stringValue = outputDirectory!.path
} else {
        outputUrl = defaultUrl!.deletingPathExtension()
        outputText.stringValue = outputUrl.path + "\(codecChosen)"
}
    return outputText.stringValue
}

现在这个函数还不能用,因为我还没有弄清楚如何调用它。但这是另一个问题,而不是我在这里问的问题。

之前我是运行

        outputUrl = defaultUrl!.deletingPathExtension()
        outputText.stringValue = outputUrl.path + "\(codecChosen)"

作为我的 inputBrowseButton @IBAction 方法的一部分,我是 运行

        let outputFile = defaultUrl!.deletingPathExtension()
        let outputFilename = outputFile.lastPathComponent
        outputUrl = outputDirectory!.appendingPathComponent(outputFilename)
        outputText.stringValue = outputUrl.path + "\(codecChosen)"

作为我的 outputBrowseButton @IBAction 方法的一部分。

效果很好,除了在更新 outputText.stringValuecodecChosen 变量在我的 @IBAction 中为 codecSelector [=16] 分配了一个新值=] 方法.

我怀疑问题是我没有将 outputText NSTextField 设置为在 codecSelector NSPopupButton 更改时进行更新。我需要做什么才能做到这一点?

How do you set the text in an NSTextField?

Which worked fine, EXCEPT when it came to updating outputText.stringValue when the codecChosen variable was assigned a new value in my @IBAction for the codecSelector NSPopupButton method.

尝试使用单独的方法更改文本。

func changeText(inputString: String, inputField: NSTextField) {
    inputField.stringValue = inputString 
}

更多地分离您的代码可能会让您在开始时更容易跟踪。我对macOS不是很熟悉,所以这个方法可能行不通,但是尝试一下它的原理,看看你能不能进步。