我有一个 NSImageView
子类,用于将文件拖放到我的应用程序中。
为此,我创建了 NSImageView
的子类,并将 NSImageView
拖到我的 XIB 上,然后设置 XIB NSImageView
的类> 反对我的自定义子类。
拖放操作一切正常,我知道拖放后我拥有正确的文件。
当我想根据拖入的文件更新 MainViewController 上的文本字段时,问题就出现了。
我创建了以下子类和协议(protocol)
#import <Cocoa/Cocoa.h>
#import <Quartz/Quartz.h>
@protocol PDFDraggedIntoWell <NSObject>
@required
-(void)PDFDraggedIntoWellWithURL:(NSURL*) importedURL;
@end
@interface DragAndDropImageView : NSImageView
@property (strong) id <PDFDraggedIntoWell> delegate;
@end
然后在子类的实现中我尝试调用委托(delegate)方法
-(void) finishedDragginInFileWithURL:(NSURL*) importedURL{
if( self.delegate != nil && [ self.delegate respondsToSelector: @selector(PDFDraggedIntoWellWithURL:)]) {
[self.delegate performSelector:@selector(PDFDraggedIntoWellWithURL:) withObject:importedURL];
}
}
我遇到的问题是如何分配委托(delegate)。从 XIB NSImageView 到我的 MainviewController,我连接了一个 IBOutlet
@property (weak) IBOutlet DragAndDropImageView *draggedFileImageView;
我已经声明我的 ViewController 将接收委托(delegate)
@interface MyMainUIViewController ()<PDFDraggedIntoWell>
实现适当的方法
-(void) PDFDraggedIntoWellWithURL:(NSURL *)importedURL{ }
现在我已经尝试在不同的地方将委托(delegate)分配给 self (在 viewDidLoad
中 - 由于 View 正在 XIB 中加载,因此不会被调用??)以及
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
但我得到的只是调试时委托(delegate)仍然为零。
我做错了什么?感谢您的帮助!!
最佳答案
如果您使用 xibx,则会调用 initWithCoder
方法进行初始化。将您的委托(delegate)设置在那里。
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
myView.delegate = self;
}
return self;
}
或者通过界面生成器设置委托(delegate),方法是按住 Ctrl 键从文件所有者拖动到您的 View 。像这样:
关于objective-c - 将 Delegate 设置为放置在 Xib 中的 NSImageView 的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12447290/