Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make an editable text field in a swift shell application

Tags:

shell

swift

cocoa

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()
like image 573
ja. Avatar asked Dec 26 '15 11:12

ja.


1 Answers

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.

like image 141
Jeff Peterson Avatar answered Oct 12 '22 23:10

Jeff Peterson