Home > other >  How to create a custom NSView for NSSavePanel in Cocoa MacOS objective C?
How to create a custom NSView for NSSavePanel in Cocoa MacOS objective C?

Time:02-26

enter image description here

I need to add a save extension selector with a text label next to it to my NSSavePanel. In the screenshot attached I try to demonstrate that I succeeded in adding an NSComboBox to my panel with the function setAccessoryView. However I have no idea how to create a custom NSView, which includes both an NSComboBox and an NSTextView or equivalent. I found no tutorials on the internet (or if I found one it was extremely outdated) showing how to create custom NSViews in objective-C in Cocoa on MacOS.

How can I create a custom NSView containing a combobox and a text label? Or how can I add two "stock" NSViews to the same NSSavePanel? Please be as detailed in your answer as possible, as I have very limited objective-c experience.

CodePudding user response:

Press Cmd-N to add a new file to your project. Choose a View file to add a xib file that has a custom view.

enter image description here

Open the xib file and add the controls to the custom view. Press the Add button in the project window toolbar to access the user interface elements.

Use the NSNib class to load the xib file and get the custom view.

CodePudding user response:

You asked how to create an NSView in Objective-C with an NSTextField and an NSComboBox as subviews.

Basically, you could define them in Interface Builder and programmatically set the resulting view in Objective-C as an accessoryView of the NSSavePanel. Alternatively, the Custom NSView could be created entirely in Objective-C, which is probably the easier option here.

After instantiating an NSView, you can use addSubview: to add an NSTextField and an NSComboBox accordingly. Then you can use NSLayoutConstraints to set up autolayout, which takes care of sizing the accessoryView and arranging the subviews properly based on the width of the dialog.

If you create the views programmatically and use autolayout, you must explicitly set translatesAutoresizingMaskIntoConstraints to NO.

Should you want to set the demo screenshot

  • Related