如何从另一个 NSView 更改 NSTextField 值(不同 swift 文件)

How to change NSTextField value from another NSView (different swift files)

我有两个不同的 NSViews.
viewAViewA.swift 控制
viewBViewB.swift
控制 我想更改 textField ( NSTextField) 位于 viewB 中,来自 viewA

我通过从 viewA 创建 viewB 的实例来更改它,但我收到错误

以下是我在 viewA 中创建实例的方式:

let myViewB = ViewB()
myViewB.changeValue = myString

并且在 viewB 中我声明:

var myString = "" {
    didSet {
        myNSTextField.stringValue(myString)
    }
}

这是我在更改 NSTextField 值时遇到的错误:

unexpectedly found nil while unwrapping an Optional value



更新:

文件ViewB.swift

class ViewB: NSView {
    ...
    @IBOutlet weak var widthTextField: NSTextField!
    ...
}

文件ViewA.swift

 let myViewB = ViewB()

 class ViewA: NSView {
     ...
     if *statement* {
          ....
          myViewB.widthTextField.stringValue("try") // <- here i get the error
          ....
     }
     ...
}

在您的代码中,您生成了一个新的 stringValue 对象(我认为)。是这样的吗?

class ViewB: NSView {
    @IBOutlet weak var widthTextField: NSTextField!
}
let myViewB = ViewB()

class ViewA: NSView {
    if *statement* {
        myViewB.widthTextField.stringValue = "try" //setting it "try" without recreating the stringValue (done by "()")
    }

}

我终于修好了!我创建了一个变量,其中包含需要将其更改为这样的文本:(使用您的测试项目)

在class视图A

    import Cocoa

var textToSet = "Hello"

class ViewA: NSView {
    override func drawRect(dirtyRect: NSRect) {
        super.drawRect(dirtyRect)

        // Drawing code here.
    }

    @IBAction func editPressed(sender: AnyObject) {
        textToSet = "No"
    }

}

在class视图B

import Cocoa

class ViewB: NSView{

    @IBOutlet var myTextField: NSTextField!
    override func drawRect(dirtyRect: NSRect) {
        super.drawRect(dirtyRect)

        myTextField.stringValue = textToSet
        // Drawing code here.
    }

}