Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

macos - OSX application without storyboard or xib files using Swift

Unfortunately, I haven't found anything useful on the Internet - I wanted to know, what code I actually have to type for initializing an application without using storyboard or XIB files in Swift. I know I have to have a .swift file called main. But I don't know what to write in there (like do I need autoreleasepool or something like that?). For example, what would I do for initializing an NSMenu and how would I add a NSViewController to the active window (iOS's similar .rootViewController doesn't help). Thanks for any help ;)

Edit: I actually don't want to use @NSApplicationMain in front of the AppDelegate. I'd rather know what exactly happens there and then do it myself.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

if you don't want to have the @NSApplicationMain attribute, do:

  1. have a file main.swift

  2. add following top-level code:

     import Cocoa
    
     let delegate = AppDelegate() //alloc main app's delegate class
     NSApplication.shared.delegate = delegate //set as app's delegate
     NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv) //start of run loop       
    
     // Old versions:
     //  NSApplicationMain(C_ARGC, C_ARGV)
     //  NSApplicationMain(Process.argc, Process.unsafeArgv);  
    

the rest should be inside your app delegate. e.g.:

import Cocoa

class AppDelegate: NSObject, NSApplicationDelegate {
    var newWindow: NSWindow?
    var controller: ViewController?
    
    func applicationDidFinishLaunching(aNotification: NSNotification) {
        newWindow = NSWindow(contentRect: NSMakeRect(10, 10, 300, 300), styleMask: .resizable, backing: .buffered, defer: false)
        
        controller = ViewController()
        let content = newWindow!.contentView! as NSView
        let view = controller!.view
        content.addSubview(view)
        
        newWindow!.makeKeyAndOrderFront(nil)
    }
}

then you have a viewController

import Cocoa

class ViewController : NSViewController {
    override func loadView() {
        let view = NSView(frame: NSMakeRect(0,0,100,100))
        view.wantsLayer = true
        view.layer?.borderWidth = 2
        view.layer?.borderColor = NSColor.red.cgColor
        self.view = view
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...