Search code examples
swiftmacosnstextfield

NSTextField not visible


I recently started coding Swift. So I am working on a macOS app to get more used to Swift.

I want that an NSTextField is created when the user presses a button. I got the code below but the NSTextField doesn't display. While research I found that it somehow must be added to view but not how this is done.

@IBAction func buttonPressed(_ sender: Any) {
    let label = NSTextField()
    label.stringValue = ("Hello World")   
}

How do I make the NSTextField display? Any help would be highly appreciated.


Solution

  • let rect = NSMakeRect(20, 20, 80, 44)
    let label = NSTextField(frame: rect)
    view.addSubview(label)
    

    Worked for me. In Xcode 10 with swift 4.