Information on how to initialize the NSTextField

Asked 2 years ago, Updated 2 years ago, 64 views

How do I substitute NSTextField for the initial value of the string before View is drawn?

OSX 10.10.1 (Yosemite) + Xcode 6.1 + Swift 1.1 is creating a program using NSTextFiled.When I tried to write a program to initialize NSTextField, I got the following error:

fatal error:unexpected found nil while unwrapping an optional value

I think the reason for the fatal error was because NSTextField.stringValue was unwrapped even though nil, but I didn't know where to initialize it

Also, the NSTextField was not able to find the code to set the initial value, perhaps because it rarely showed the initial value.I read the article that if it is Objective-C, it will be initialized with AppDelegate, but Swift said it should be ViewController, so I didn't understand it well.

I tried to move the following code in playground

import Cocoa

var str = "Hello, playground"
var strnil —String!=nil

strnil = str
println("\"(strnil)")

seemed to work without any problems.Therefore, I imagine that the settings around the ViewController and Storyboard are bad, or that the initialization position is bad...
Here is a sample of the Storyboard screen and the code:AppDelegate remains the default.
Thank you for your cooperation.

import Cocoa
    
    classViewController:NSViewController {
    
        @IBOutlet weak var textField:NSTextField!
        
        override func viewDidLoad(){
            super.viewDidLoad()
    
            // Do any additional setup after loading the view.
        }
    
        override var presentedObject:AnyObject?{
            DidSet{
            // Update the view, if already loaded.
            }
        }
    
        required init?(coder:NSCoder) {
            // fatalError ("init(coder:) has not been implemented")
            
            super.init (coder:coder)
            
            textField.stringValue="a string"
    
        }
    }

Storyboard View

macos objective-c swift

2022-09-30 20:10

1 Answers

Just like iOS, I think you can use viewDidLoad().
The textField is not available yet because the outlet connection has not been completed at the init stage.These preparations are completed by viewDidLoad() (awakeFromNib() in NSViewController.

Also, when using storyboard, AppDelegate can connect only to ui in Application Scene in storyboard.
Apple's policy seems to be to set up ui with the NSViewController that manages the view.


2022-09-30 20:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.