programmatically loading object from subclass of NSView from nib

后端 未结 5 801
闹比i
闹比i 2020-12-24 02:56

How do I correctly load an object that is a subclass of NSView using a Xib?

I want it to be loaded dynamically not from the beginning so I made a MyView.Xib From MyD

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-24 03:55

    I found the answer by @Bavarious very useful, but it still needed some squirrelling on my part to make it work for my use case - load one of several xib's view definitions into an existing "container" view. Here's my workflow:

    1) In the .xib, create the view in IB as expected.

    2) DO NOT add an object for the new view's viewController, but rather

    3) Set the .xib's File's Owner to new view's viewController

    4) Connect any outlets & actions to File's Owner, and, specifically, .view

    5) Call loadInspector (see below).

    enum InspectorType {
        case None, ItemEditor, HTMLEditor
    
        var vc: NSViewController? {
            switch self {
            case .ItemEditor:
                return ItemEditorViewController(nibName: "ItemEditor", bundle: nil)
            case .HTMLEditor:
                return HTMLEditorViewController(nibName: "HTMLEditor", bundle: nil)
            case .None:
                return nil
            }
        }
    }
    
    class InspectorContainerView: NSView {
    
        func loadInspector(inspector: InspectorType) -> NSViewController? {
            self.subviews = [] // Get rid of existing subviews.
            if let vc = inspector.vc {
                vc.loadView()
                self.addSubview(vc.view)
                return vc
            }
            Swift.print("VC NOT loaded from \(inspector)")
            return nil
        }
    }
    

提交回复
热议问题