0

I am trying to implement NSStackView with always the same custom view. So I have define my xib file, linked everything inside my class, associated the class, ... but I am sure I am missing something because the content inside the view don't appear. Thx very much for your help.

My storyboard: enter image description here

My xib file: enter image description here

The result when I run the below code: enter image description here

My file is like :

class CustomView: NSView, NSTableViewDelegate, NSTableViewDataSource {
    @IBOutlet weak var segmentControlOutlet: NSSegmentedControl!
    @IBOutlet weak var tableViewOutlet: NSTableView!
}

class ViewController: NSViewController, NSStackViewDelegate {
    
    @IBOutlet weak var stackViewOutlet: NSStackView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        stackViewOutlet.delegate = self
        
        let newView = CustomView()
        stackViewOutlet.addArrangedSubview(newView)
        
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }


}
koen
  • 5,383
  • 7
  • 50
  • 89
MrPOHB
  • 31
  • 4
  • try adding some constraints to the stack view. I ran a quick test here and without the constraints, the stack shrank down to zero height and zero width, so it was invisible. you can also add colours to the backgrounds when trying to debug view problems. – john elemans Mar 28 '20 at 16:51
  • Thx for your reply, the stack view is constrain to the border of the window, so in theory it should appear. But indeed, when i ask for the fitting sizeof newView, i have 0.0 as height and width ... – MrPOHB Mar 28 '20 at 17:41

1 Answers1

1

I have found the answer, you need to initiate properly the view. To do so :

class CustomView: NSView, NSTableViewDelegate, NSTableViewDataSource {

    @IBOutlet var viewOutlet: NSView!
    @IBOutlet weak var segmentControlOutlet: NSSegmentedControl!
    @IBOutlet weak var tableViewOutlet: NSTableView!

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        Bundle.main.loadNibNamed("CustomView", owner: self, topLevelObjects: nil)
        addSubview(viewOutlet)
        viewOutlet.frame = self.bounds
        viewOutlet.autoresizingMask = [.height, .width]
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        Bundle.main.loadNibNamed("CustomView", owner: self, topLevelObjects: nil)
        addSubview(viewOutlet)
        viewOutlet.frame = self.bounds
        viewOutlet.autoresizingMask = [.height, .width]
    }

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        // Drawing code here.
    }
}

Please take car that when you load the nib name, "CustomView" is the name of your xib file ;)

MrPOHB
  • 31
  • 4