I want to put a custom control inside the view for my NSCollectionViewItem.
Lets say I have a custom NSView called BoxesView.BoxesView is just a view that draws a predetermined number of boxes in its view. That number of boxes is set in the init method. Lets say I set it to 8.
When I load up the collection view, all the o开发者_StackOverflowther controls in the view work fine, (buttons, sliders, etc.) but my view won't draw.
If I set a breakpoint in the drawRect method of BoxesView it shows that the number of boxes to draw is 0! If I set a breakpoint in my init method where I set numBoxes to 8, it shows that numBoxes does actually get set to 8. Also, the init method only gets called 1 time even though there are multiple rows in the collection view.
What am I doing wrong?
UPDATE
I was able to get this working by setting the itemPrototype to load from a xib instead of being in the same xib as the NSCollectionViewItem. This is great, except it only works on 10.6 and not 10.5.
UPDATE 2
What I'm trying to do, is stick my custom view inside the view that already existed for the NSCollectionViewItem that already exists. What happens is the member variable mBoxWidth gets blown away and is zero so when it goes to draw it, nothing happens.
@implementation DumbView
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
mBoxWidth = 3;
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect {
NSRect bounds = self.bounds;
[[NSColor redColor]set];
[NSBezierPath fillRect:NSMakeRect(bounds.origin.x, bounds.origin.y, mBoxWidth, mBoxWidth)];
}
@end
I didn't implement initWithCoder. That fixes everything.
NSCollectionViewItem uses a prototype view, which is duplicated and wired up for each item in the collection's represented objects.
You could go through all the trouble to make an IBPlugin for your custom view (one that exposes the numberOfBoxesToDraw binding), but that's a pain in the ass and there's an easier way: manual bindings.
Using Manual Bindings with NSCollectionView/Item
First, subclcass NSCollectionViewItem, tell IB to use this new subclass, and make sure you have an outlet in it (like boxView) that is connected to your custom view.
Next, subclass NSCollectionView (set IB to use this subclass) and override -newItemForRepresentedObject:. In it, you'll first call super (storing the result to a local variable), then manually bind your "boxView"'s number of boxes to the represented object with the "numberOfBoxes" key you're using in your model.
Have you tried overloading copyWithZone?
I'm guessing your item is getting copied and not directly init'd.
精彩评论