Michael Rivers Michael Rivers - 21 days ago 9
Swift Question

Swift Instantiate NSView from .xib file

I have created an HeadView.xib file and it's class file HeadView.swift. In the xib file I have the class set to HeadView.

In my ViewController I am calling the following code:

var myHeadView: HeadView?

@IBAction func buttonClicked(sender : NSButton?) {
let myrect = CGRect(x: 0, y: 0, width: 350, height: 350)
posView = POSView.init(frame:myrect)
}


The Compiler is complaining with the following errors:


Expected member name or constructor call after type name and

'()' is not convertible to 'HeadView'


In my HeadView Class I was hoping to instantiate the xib file with the following code

class HeadView: NSView {

init(frame frameRect: NSRect) {
super.init(frame:frameRect)

var viewArray: NSArray?

NSBundle.mainBundle().loadNibNamed("HeadView", owner: nil, topLevelObjects: &viewArray)

return viewArray.ObjectAtIndex(0)
}
}


In Swift what does init return? Is there a better way to instantiate the view from file?

Answer Source

you don't call init in Swift

posView = POSView.init(frame:myrect)

should be

posView = POSView(frame:myrect)