objective-c - 在 NSOutlineView 中拖放的问题

标签 objective-c cocoa nsoutlineview

我遇到的问题是我有一个带拖放功能的 NSOutlineView(请参阅帖子底部的代码来进行拖放工作),它可以工作,但是当我将一行拖到另一行时,被拖动的行变成了 child ,但它也停留在它作为 parent 的地方,当我删除任何一行时,它们都会被删除。 为了向您展示我的意思,我已经记录了问题,这是链接 - http://dvlp.me/6kya9

下面是在大纲 View 中进行拖放操作的代码。

头文件。

@interface _NSControllerTreeProxy : NSObject 
{
    // opaque
}
//
// Number of objects at the root level.
//
- (unsigned int)count;

- (id)nodeAtIndexPath:(id)fp8;
- (id)objectAtIndexPath:(id)fp8;
@end

@interface _NSArrayControllerTreeNode : NSObject
{
    // opaque
}
- (unsigned int)count;
- (id)observedObject;
- (id)parentNode;
- (id)nodeAtIndexPath:(id)fp8;
- (id)subnodeAtIndex:(unsigned int)fp8;
- (BOOL)isLeaf;
- (id)indexPath;
- (id)objectAtIndexPath:(id)fp8;
@end

// some more detailed reverse engineering is available here
// http://www.blueboxmoon.com/wiki/?page=Binding%20Tree


@interface DragController : NSObject
{
    IBOutlet NSTreeController *groupTreeControl;
    IBOutlet NSOutlineView *treeTable;

    NSArray* dragType;

    _NSArrayControllerTreeNode* draggedNode;


}

- (void) resortGroups:(NSManagedObjectContext*)objectContext forParent:(NSManagedObject*)parent;
- (NSArray* ) getSubGroups:(NSManagedObjectContext*)objectContext forParent:(NSManagedObject*)parent;
- (BOOL) category:(NSManagedObject* )cat isSubCategoryOf:(NSManagedObject* ) possibleSub;

@end

#define INTERVAL 10

实现文件。

@implementation DragController
- (void)awakeFromNib {  

    dragType = [NSArray arrayWithObjects:   @"factorialDragType", nil];

    [ dragType retain ]; 

    [ treeTable registerForDraggedTypes:dragType ];
    NSSortDescriptor* sortDesc = [[NSSortDescriptor alloc] initWithKey:@"position" ascending:YES];
    [groupTreeControl setSortDescriptors:[NSArray arrayWithObject: sortDesc]];
    [ sortDesc release ];
}   


//------------------------------------
#pragma mark NSOutlineView datasource methods -- see NSOutlineViewDataSource
//---------------------------------------------------------------------------   
- (BOOL) outlineView : (NSOutlineView *) outlineView 
          writeItems : (NSArray*) items 
        toPasteboard : (NSPasteboard*) pboard {

    [ pboard declareTypes:dragType owner:self ];        
    // items is an array of _NSArrayControllerTreeNode see http://theocacao.com/document.page/130 for more info
    draggedNode = [ items objectAtIndex:0 ];

    return YES; 
}




- (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(int)index {

    _NSArrayControllerTreeNode* parentNode = item;
    _NSArrayControllerTreeNode* siblingNode;
    _NSControllerTreeProxy* proxy = [ groupTreeControl arrangedObjects ];

    NSManagedObject* draggedGroup = [ draggedNode observedObject ];

    BOOL draggingDown = NO;
    BOOL isRootLevelDrag = NO;

    // ----------------------
    // Setup comparison paths
    // -------------------------
    NSIndexPath* draggedPath = [ draggedNode indexPath ];
    NSIndexPath* siblingPath =  [ NSIndexPath indexPathWithIndex:  index  ];
    if ( parentNode == NULL ) {     
        isRootLevelDrag = YES;
    } else {
        // A non-root drag - the index value is relative to this parent's children
        siblingPath = [ [ parentNode indexPath ] indexPathByAddingIndex: index ];
    }

    // ----------------------
    // Compare paths - modify sibling path for down drags, exit for redundant drags
    // -----------------------------------------------------------------------------    
    switch ( [ draggedPath compare:siblingPath] ) {
        case NSOrderedAscending:  // reset path for down dragging
            if ( isRootLevelDrag ) {
                siblingPath = [ NSIndexPath indexPathWithIndex: index  - 1];                             
            } else {
                siblingPath = [ [ parentNode indexPath ] indexPathByAddingIndex: index - 1 ]; 
            }
            draggingDown = YES;
            break;

        case NSOrderedSame:
            return NO;
            break;               
    }

    siblingNode = [ proxy nodeAtIndexPath:siblingPath ];    

    //  NSLog(@"returning early");
    //  return NO;  // TODO robustify


    // ------------------------------------------------------------ 
    // SPECIAL CASE: Dragging to the bottom
    // ------------------------------------------------------------
    // - K                               - K                            - C                              - C
    // - - U                             - - C     OR     - U                                - F
    // - - C     ====>     - - F                    - F                              - K
    // - - F               - U              - K                              - U
    // ------------------------------------------------------------ 
    if ( isRootLevelDrag  && siblingNode == NULL ) {        
        draggingDown = YES;
        siblingPath = [ NSIndexPath indexPathWithIndex: [ proxy count ] - 1 ];          
        siblingNode = [ proxy nodeAtIndexPath:siblingPath ] ;
    }

    // ------------------------------------------------------------ 
    // Give the dragged item a position relative to it's new sibling
    // ------------------------------------------------------------ 
    NSManagedObject* sibling = [ siblingNode observedObject ];   
    NSNumber* bystanderPosition = [ sibling valueForKey:@"position"];
    int newPos =   ( draggingDown ? [ bystanderPosition intValue ]  + 1 : [ bystanderPosition intValue ]  - 1 );
    [draggedGroup setValue:[ NSNumber numberWithInt:newPos ] forKey:@"position"];   

    // ----------------------------------------------------------------------------------------------
    // Set the new parent for the dragged item, resort the position attributes and refresh the tree
    // ----------------------------------------------------------------------------------------------    
    [ draggedGroup setValue:[ parentNode observedObject ] forKey:@"parent" ];
    [ self resortGroups:[draggedGroup managedObjectContext] forParent:[ parentNode observedObject ] ];          
    [ groupTreeControl rearrangeObjects ];  
    return YES;             
}






- (NSArray* ) getSubGroups:(NSManagedObjectContext*)objectContext forParent:(NSManagedObject*)parent {
    NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"projects" inManagedObjectContext:objectContext];

    [request setEntity:entity];
    NSSortDescriptor* aSortDesc = [[NSSortDescriptor alloc] initWithKey:@"position" ascending:YES];
    [request setSortDescriptors:[NSArray arrayWithObject: aSortDesc] ];
    [aSortDesc release];

    NSPredicate* validationPredicate = [NSPredicate predicateWithFormat:@"parent == %@", parent ];

    [ request setPredicate:validationPredicate ];

    NSError *error = nil;  // TODO - check the error bozo
    return [objectContext executeFetchRequest:request error:&error];    
}




- (void) resortGroups:(NSManagedObjectContext*)objectContext forParent:(NSManagedObject*)parent {

    NSArray *array = [ self getSubGroups:objectContext forParent:parent ];

    // Reset the indexes...
    NSEnumerator *enumerator = [array objectEnumerator];
    NSManagedObject* anObject;
    int index = 0;
    while (anObject = [enumerator nextObject]) {
        // Multiply index by 10 to make dragging code easier to implement ;) ....
        [anObject setValue:[ NSNumber numberWithInt:(index * INTERVAL ) ] forKey:@"position"];    
        index++;
    }   


}

- (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(int)index {

    _NSArrayControllerTreeNode* newParent = item;

    // drags to the root are always acceptable
    if ( newParent == NULL ) {  
        return  NSDragOperationGeneric; 
    }

    // Verify that we are not dragging a parent to one of it's ancestors
    // causes a parent loop where a group of nodes point to each other and disappear
    // from the control 
    NSManagedObject* dragged = [ draggedNode observedObject ];      
    NSManagedObject* newP = [ newParent observedObject ];

    if ( [ self category:dragged isSubCategoryOf:newP ] ) {
        return NO;
    }       

    return NSDragOperationGeneric;
}

- (BOOL) category:(NSManagedObject* )cat isSubCategoryOf:(NSManagedObject* ) possibleSub {

    // Depends on your interpretation of subCategory ....
    if ( cat == possibleSub ) { return YES; }

    NSManagedObject* possSubParent = [possibleSub valueForKey:@"parent"];   

    if ( possSubParent == NULL ) {  return NO; }

    while ( possSubParent != NULL ) {       
        if ( possSubParent == cat ) { return YES;   }

        // move up the tree
        possSubParent = [possSubParent valueForKey:@"parent"];          
    }   

    return NO;
}




// This method gets called by the framework but the values from bindings are used instead
- (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item { 
    return NULL;
}

/* 
 The following are implemented as stubs because they are required when 
 implementing an NSOutlineViewDataSource. Because we use bindings on the
 table column these methods are never called. The NSLog statements have been
 included to prove that these methods are not called.
 */
- (int)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item {
    NSLog(@"numberOfChildrenOfItem");
    return 1;
}

- (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item {
    NSLog(@"isItemExpandable");
    return NO;
}

- (id)outlineView:(NSOutlineView *)outlineView child:(int)index ofItem:(id)item {
    NSLog(@"child of Item");
    return NULL;
}



@end

最佳答案

只是四处搜索了一下,找到了解决方法。 在 NSTreeController 的属性中,将获取谓词设置为 parent == nil

关于objective-c - 在 NSOutlineView 中拖放的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1227795/

相关文章:

objective-c - iPad 应用程序。退出(0)留在 'taskbar'

iphone - 编码问题 : Cocoa Error 261?

ios - UIImage 从 json 请求返回 nil 到 tableView 单元格图像的 mysql 数据库?

objective-c - 哪个方法名称最符合 Objective-C/Cocoa 约定?

swift - NSOutlineView拖线卡住+蓝色边框

objective-c - NSOutlineView reloadData 关闭我的 NSPopOver

objective-c - 如何在主队列或线程上分派(dispatch)带有参数的 block

objective-c - 更新 NSDocument 状态而不撤消?

objective-c - 强制某个类发布特定的 NSNotification?

objective-c - 基于 View 的 NSOutlineView 并显示标题单元格