Search code examples
swiftmacosnsviewnstextfield

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


I have two different NSViews.
viewA is controlled from ViewA.swift
viewB is controlled from ViewB.swift
I want to change textField (NSTextField) that is in viewB from viewA.

i change it by creating an instance of viewB from viewA, but i get an error

Here is how i create the instance in viewA:

let myViewB = ViewB()
myViewB.changeValue = myString

And in viewB i declared:

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

This is the error I get when i change the NSTextField value:

unexpectedly found nil while unwrapping an Optional value



UPDATE:

file ViewB.swift

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

file ViewA.swift

 let myViewB = ViewB()

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

Solution

  • I finally fixed it! I create one variable which contains the text it needs to change it to like this: (using your test-project)

    In class ViewA

        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"
        }
    
    }
    

    In class ViewB

    import Cocoa
    
    class ViewB: NSView{
    
        @IBOutlet var myTextField: NSTextField!
        override func drawRect(dirtyRect: NSRect) {
            super.drawRect(dirtyRect)
    
            myTextField.stringValue = textToSet
            // Drawing code here.
        }
    
    }