将Delegate设置为放置在Xib中的NSImageView的子类

时间:2012-09-16 13:35:21

标签: objective-c xcode macos cocoa delegates

我有一个NSImageView子类,用于在我的应用中拖放文件。

为此,我创建了一个NSImageView的子类,并将NSImageView拖到我的XIB上,然后将XIB NSImageView对象的类设置为我的自定义子类。

一切都适用于拖放,我知道拖动后我有正确的文件。

当我想根据拖入的文件更新MainViewController上的文本字段时出现问题。

我创建了以下子类和协议

#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

然后在我的子类实现中,我尝试调用委托方法

-(void) finishedDragginInFileWithURL:(NSURL*) importedURL{
    if( self.delegate != nil && [ self.delegate respondsToSelector: @selector(PDFDraggedIntoWellWithURL:)]) {
        [self.delegate performSelector:@selector(PDFDraggedIntoWellWithURL:) withObject:importedURL];
    }
}

我遇到的问题是你如何分配代表。从XIB NSImageView到我的MainviewController,我连接了IBOutlet

@property (weak) IBOutlet DragAndDropImageView *draggedFileImageView;

我已声明我的ViewController将收到委托

@interface MyMainUIViewController ()<PDFDraggedIntoWell>

实施适当的方法

-(void) PDFDraggedIntoWellWithURL:(NSURL *)importedURL{   }

现在我已尝试在各个地方将委托分配给self(在viewDidLoad中 - 由于视图正在XIB中加载而不会被调用?)以及

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

但我回来的是调试时委托仍然是零。

我做错了什么?谢谢你的帮助!!

2 个答案:

答案 0 :(得分:0)

如果您使用的是xibx,则会调用initWithCoder方法进行初始化。在那里设置你的代表。

- (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;
}

或者通过界面构建​​器设置委托,方法是将文件所有者的控制权拖动到视图中。像这样:
enter image description here

答案 1 :(得分:0)

我能够添加委托给awakefromnib(在mymainviewcontroller中)方法,现在情况正常。感谢

相关问题