10

I'm trying to make a editable text region in a NSWindow. So far I can make a window and add a text field - but when I select it and type characters the characters are echoed in the shell and NOT the text area.

NOTE: this is NOT an Xcode project - I am trying to do this in a single file in the shell - my goal is to do this in code only

To replicate the error put the following code into a file (experiment.swift) and give the shell command

> swift experiment.swift

Here's the code


import Cocoa

class MyAppDelegate: NSObject, NSApplicationDelegate {

  let window = NSWindow()
  let ed = NSTextField(frame: NSMakeRect(20, 10, 180, 160))

  func applicationDidFinishLaunching(aNotification: NSNotification) {

    window.setContentSize(NSSize(width:600, height:200))
    window.styleMask = NSTitledWindowMask | NSClosableWindowMask |
                       NSMiniaturizableWindowMask |
                       NSResizableWindowMask

    window.opaque = false
    window.center();
    window.title = "My window"

    ed.font = NSFont(name:"Helvetica Bold", size:20)
    ed.stringValue = "edit me"
    ed.editable = true
    ed.selectable = true

    window.contentView!.addSubview(ed)

    window.makeKeyAndOrderFront(window)
    window.level = 1
}

func applicationWillTerminate(aNotification: NSNotification) {
    // Insert code here to tear down your application
}

}

let app = NSApplication.sharedApplication() 
let obj = MyAppDelegate()

app.delegate = obj
app.run()

1 Answer 1

5

Before app.run(), add

app.setActivationPolicy(.Regular)

According to the docs, the default activationPolicy is Prohibited:

  • Prohibited

The application does not appear in the Dock and may not create windows or be activated. [...] This is also the default for unbundled executables that do not have Info.plists.

1
  • This helps - now I can edit in the window but when I press carriage return the entire line is selected and a new line is not created.
    – ja.
    Dec 26, 2015 at 13:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.