Passing values from custom NSView to NSCollectionViewItem
I have an NSTabView inside my custom NSView that is used as the prototype for the NSCollectionView. In the second tab I have NSButton button and NSImageView objects.
NSButton is a "Browse" button that triggers the NSOpenPanel.
I have connected the button's selector to IBAction in MyCustomView which performs the following:
// MyView.h
@interface MyView : NSView
{
IBOutlet NSTabView *tabView;
IBOutlet NSImageView *myImageView;
IBOutlet NSButton *browseButton;
}
-(IBAction)openBrowseDialog:(id)sender;
@end
// MyView.m
-(IBAction)openBrowseDialog:(id)sender
{
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setCanChooseFiles:YES];
[openDlg setCanChooseDirectories:NO];
[openDlg setAllowsMultipleSelection:NO];
[openDlg setAllowedFileTypes:[NSArray arrayWithObjects:@"png", @"jpg", @"jpeg", @"gif", nil]];
if ( [openDlg runModal] == NSOKButton )
{
NSArray* files = [openDlg URLs];
NSURL* fileURL = [files objectAtIndex:0];
NSData *imageData = [NSData dataWithContentsOfURL:fileURL];
if( imageData != nil )
{
NSImage *image = [[NSImage alloc] initWithData:imageData];
myImageView.image = 开发者_如何学JAVAimage;
[image release];
}
}
}
When I run this "myImageView" traces "null" in the Console even though I connected it as IBOutlet in Interface Builder. Could you explain why? How should I do this instead? I also need to pass the "fileURL" value to "representedObject" in my NSCollectionViewItem object but I don't know how to access that from here?
I have finally achieved what I needed after a day of trouble-shooting. There were a couple of things wrong with my original approach:
1) Using NSTabView inside NSCollectionView appears to be a bad idea because bindings do not get initialized in "non-active" tabs. I scrapped that and opted for NSSegmentedControl instead with manual show/hide of objects.
2) All of the code in my original question should really go inside subclass of NSCollectionViewItem rather than into subclass of NSView, which I don't even need since I'm not doing custom drawing.
Now it's all good. I'm learning.
精彩评论