Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Nib Support
/*
ericasadun.com
Playground Support for NIB-based interaction: Add to playground's Sources folder
*/
import Cocoa
import XCPlayground
/// Generate a playground-specific command-line request to compile the xib file
public func DisplayCompileCommand() {
let path = NSBundle.mainBundle().bundlePath.stringByAppendingPathComponent("Contents/Resources")
println("cd \"\(path)\"; ibtool --compile MainMenu.nib MainMenu.xib")
}
/// Delegate root class
public class Delegate : NSObject {} ; public var delegate = Delegate()
/// Read in nib to item array. Use NSBundle vs UINib/NSNib to avoid playground crashes
public func LoadItemArrayFromNib() -> NSArray {
var itemArray = NSArray()
var itemArrayPointer = AutoreleasingUnsafeMutablePointer<NSArray?>(&itemArray)
NSBundle.mainBundle().loadNibNamed("MainMenu", owner: nil, topLevelObjects: itemArrayPointer)
return itemArray
}
/// Fetch item by class
public func SelectTypedItemFromArray<T>(type t: T.Type, array: NSArray) -> T? {
for eachItem in array {
if let typedItem = eachItem as? T {
return typedItem
}
}
return nil
}
/// Playground-accessible global nib item array
public var nibItemArray = LoadItemArrayFromNib()
/// Playground-accessible global main window
public var window : NSWindow! = SelectTypedItemFromArray(type: NSWindow.self, nibItemArray)
/// Playground-accessible global content view for main window
public var contentView = window.contentView as! NSView
/// Fetch view by tag and class from contentView
public func FetchView<T>(type t: T.Type, tag: Int = 0, contentView: NSView = contentView) -> T? {
if tag != 0 {
// When the tag is specified, the subview must match that tag
if let view : T = contentView.viewWithTag(tag) as? T {return view}
} else {
// When the tag is 0 or unspecified, find by type using depth-first recursion
for eachItem in contentView.subviews {
if let view = eachItem as? T {return view}
if let subview = FetchView(type: t.self, tag:0, contentView:eachItem as! NSView) {
return subview
}
}
}
return nil
}
/// Load nib and establish playground runloop
public func Launch() {
XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)
window.level = 7
NSApplication.sharedApplication().setActivationPolicy(.Regular)
}
@jprattx
Copy link

jprattx commented Dec 6, 2018

/* updated example of retrieving topLevelObjects from loaded nib, for Swift 4 */

var itemArray = NSArray()
let itemArrayPointer = AutoreleasingUnsafeMutablePointer<NSArray?>(&itemArray)
Bundle.main.loadNibNamed("MainMenu", owner: nil, topLevelObjects: itemArrayPointer)

// print contents of toplevelobjects
print(itemArray)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment