开发者

Adding a custom view to toolbar

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 works perfectly). IB automatically created a NSToolbarItem. I followed the instructions from Apple here: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Toolbars/Tasks/AddRemoveToolbarItems.html#//apple_ref/doc/uid/20000755-BBCGJCDJ

The problem is that I don't know what to do now, the view doesn't show al开发者_高级运维though it's label is displayed in the window.

Here's the code I use to draw (very simple, it's for testing purpose)

- (void)drawRect:(NSRect)dirtyRect {
    [[NSColor blackColor] set];
    [[NSBezierPath bezierPathWithRect:self.bounds] fill];
}

Can someone help me?

Thanks in advance.


I solved the problem.

I put my custom view in the root of the nib. I added a classic NSToolbarItem and created two outlets: one for the custom view and one for the NSToolbarItem. On -(void)awakeFromNib, I called setView: on the NSToolbarItem with the custom view.

According to some ressources on the internet, it is a bug with Interface Builder.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜