0

我正在使用 NSView 委托来读取拖动的 excel 值。为此,我将 NSView 子类化。我的代码就像-

@interface SSDragDropView : NSView
    {
        NSString *textToDisplay;
    }
    @property(nonatomic,retain) NSString *textToDisplay; // setters/getters

    @synthesize textToDisplay;// setters/getters

    @implementation SSDragDropView
    - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender{
        [self setNeedsDisplay: YES];
        return NSDragOperationGeneric;
    }

    - (void)draggingExited:(id <NSDraggingInfo>)sender{
        [self setNeedsDisplay: YES];
    }

    - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender {
        [self setNeedsDisplay: YES];
        return YES;
    }


   - (BOOL)performDragOperation:(id < NSDraggingInfo >)sender {
        NSArray *draggedFilenames = [[sender draggingPasteboard] propertyListForType:NSFilenamesPboardType];
        if ([[[draggedFilenames objectAtIndex:0] pathExtension] isEqual:@"xls"]){
            return YES;
        } else {
            return NO;
        }
    }

    - (void)concludeDragOperation:(id <NSDraggingInfo>)sender{
        NSArray *draggedFilenames = [[sender draggingPasteboard] propertyListForType:NSFilenamesPboardType];
        NSURL *url =   [NSURL fileURLWithPath:[draggedFilenames objectAtIndex:0]];
       NSString *textDataFile = [NSString stringWithContentsOfURL:url usedEncoding:nil error:nil]; //This text is the original excel text and its getting displayed.
    [self setTextToDisplay:textDataFile];
       }

我将 textDataFile 值设置为该类的字符串属性。现在我在其他一些类中使用 SSDragDropView 属性值,例如-

SSDragDropView *dragView = [SSDragDropView new];
    NSLog(@"DragView Value is %@",[dragView textToDisplay]); 

但我每次都为空。是不是我不能在那些委托方法中设置属性值?

4

2 回答 2

0

只需在 SSDragDropView.h 类中声明一个全局变量即可解决上述问题。

#import <Cocoa/Cocoa.h>
NSString *myTextToDisplay;
@interface SSDragDropView : NSView
{

可以在所需的委托方法中设置相同的

- (void)concludeDragOperation:(id <NSDraggingInfo>)sender {

// .... //Your Code
NSString *textDataFile = [NSString stringWithContentsOfURL:url usedEncoding:nil error:nil];
myTextToDisplay = textDataFile;
// .... //Your Code
}

:)

于 2013-05-23T10:29:19.313 回答
0

添加

[dragView registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, nil]];  

- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender{

    NSPasteboard *pboard = [sender draggingPasteboard];
    NSArray *paths = [pboard propertyListForType:NSFilenamesPboardType];
    NSLog(@"%@",paths);
    [self setNeedsDisplay: YES];
    return NSDragOperationGeneric;
}  

下面的代码将打印 nil,因为您没有在 NSView 上拖动任何内容。

SSDragDropView *dragView = [SSDragDropView new];
    NSLog(@"DragView Value is %@",[dragView textToDisplay]); 
于 2013-05-21T11:16:58.037 回答