
Question:
I have defined a custom class with a drawRect called Drawing. I have laid out the view in my NIB to contain an NSScrollView with a Drawing subview. When I launch the program, the screen is blank. Interestingly, when I create the documentView for the NSScrollView programmatically, I get an image in my scroll view. When I use the instance for the nib in my setDocumentView, I get nothing.
So if the Drawing view is set in IB,
[_scrollViewWorkspace setDocumentView:_drawing]; //does not work.
But
[_scrollViewWorkspace setDocumentView:[[Drawing alloc] initWithFrame:NSMakeRect(0,0,[[_scrollViewWorkspace documentView ]bounds].size.width, [[_scrollViewWorkspace documentView] bounds ].size.height)]];
Works great!
Why can't I statically bind a drawing object in a NIB?
Answer1:When you set the custom class of the NSView
subclass in the nib file to your custom class, at runtime, an instance of that class will be created using initWithCoder:
rather than initWithFrame:
.
You can easily check to see if this is the case by adding the following method to your custom Drawing
view:
- (id)initWithCoder:(NSCoder *)coder {
NSLog(@"[%@ %@]", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
return [super initWithCoder:coder];
}
Then launch your app and see if [Drawing initWithCoder:]
is logged to the console.
If you have overridden initWithFrame:
in your Drawing
class to do custom initialization (like set a custom image automatically), you will need to add that same code to the initWithCoder:
method so that you end up with the same result:
- (id)initWithCoder:(NSCoder *)coder {
if ((self = [super initWithCoder:coder])) {
// do custom initialization here
}
return self;
}
Answer2:Solved!
When I laid the view out in Interface Builder I just dragged the custom view to the NSScrollView in the canvas. I re-did the layout so that I used Embed->Scroll View and it worked.
Bruce