Adding a custom view to toolbar

后端 未结 2 769
你的背包
你的背包 2021-02-07 15:10

I\'m struggling with Cocoa for 2 hours now without success. I want to add a custom view to the toolbar. So, I added a NSToolbar to the window (with IB), and added my view (which

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-07 15:40

    According to an Apple engineer in the discussion at http://www.mail-archive.com/cocoa-dev@lists.apple.com/msg35673.html, there is a bug in Interface Builder whereby "Custom Views" (NSViews created in IB) are not decoded properly when used as the view for an NSToolbarItem, and so do not appear in the toolbar. Other kinds of NSViews, such as NSButtons and NSBoxes, will work just fine as toolbar items: you can create these in Interface Builder and then drag them into the toolbar to make them into toolbar items.

    (The discussion in the link above implies that the bug is down to how "Custom Views" are created from the XIB at runtime: using initWithFrame: instead of initWithCoder:. The discussion dates from 2009 but this still hasn't been fixed as of XCode 4.5/OS X 10.8.)

    In my case I was using a regular NSView to wrap a set of controls (a volume slider and min/max buttons), rather than implementing a custom NSView subclass. I was able to avoid the problem by using an NSBox as the container instead of an NSView: I made the NSBox transparent, title-less and borderless, so it otherwise acted exactly like a plain NSView wrapper. This was a little more work in IB, but saved me the trouble of wiring up the view to the toolbar item programmatically.

提交回复
热议问题