Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

cocoa - How to add custom NSView with xib to NSViewController

I want to create generic custom NSView with xib which i want use all over application wherever it needed. write now I want to add it to NSViewController view. I need functionality where I can just assign this custom NSView class inside storyboard to any view.

I need something like this:

  1. NSViewController
  2. View
  3. Subview (I will mark this view as custom NSView through storyboard)

This is my code:

class TestCustomView: NSView {

@IBOutlet var contentView: NSView!

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

override init(frame frameRect: NSRect) {
    super.init(frame: frameRect)
    
    Bundle.main.loadNibNamed("TestCustomView", owner: self, topLevelObjects: nil)
    let contentFrame = NSMakeRect(0, 0, frame.size.width, frame.size.height)
    self.contentView.frame = contentFrame
    self.addSubview(contentView)
    
}

required init?(coder: NSCoder) {
    super.init(coder: coder)
}   

}

With this code I am able to add custom view, but when I add subview inside this custom view its not visible. secondly to add this view I need to add it programmatically like this:

let testCustomView = TestCustomView(frame: CGRect(x: 0, y: 0, width: 548, height: 400))
     testCustomView.translatesAutoresizingMaskIntoConstraints = false
     mysubview.addSubview(testCustomView)

So basically what things Im missing here, I don't want this programmatic approach. I want set it through storyboard only. I have gone through lot of articles but didn't found satisfactory answer.

question from:https://stackoverflow.com/questions/65902937/how-to-add-custom-nsview-with-xib-to-nsviewcontroller

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

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...