一步一步熟悉Mac app開發(fā)(六)之NSOutlineView

概要

階段一,完成數(shù)據(jù)的顯示。
階段二卿操,完成數(shù)據(jù)拖拽的調(diào)整。(存在未知問題)
階段三傻挂,實現(xiàn)撤銷功能。(存在問題)

階段一 實現(xiàn)數(shù)據(jù)的顯示

1.新建項目挖息,打開storyboard金拒,將source list拖拽直默認的view controller中。


image.png

2.將tree controller和object拖拽至默認的view controller的頂部旋讹。(不會的請看前文)


image.png

3.點擊選中object殖蚕,設(shè)置其【Custom Class】為“NSMutableArray”,設(shè)置其【Document Label】為playlits沉迹。


image.png

4.點擊選中Tree Controller睦疫,按住Control鍵將其拖拽至object圖標上,選擇content鞭呕。


image.png

5.點擊選中Tree Controller蛤育,設(shè)置其Children為children、Ledf為isLeaf、Class Name為Playlist瓦糕。(聰明的你知道我們下一步要做什么了嗎底洗?)


image.png

6.新建一個NSObject的子類Playlist,聲明兩個屬性name和creator咕娄,聲明并實現(xiàn)isLeaf和初始化方法亥揖。

//Playlist.h
#import <Cocoa/Cocoa.h>
@interface Playlist : NSObject
@property NSString *name;
@property NSString *creator;
- (bool) isLeaf;
- (id) init;
- (id) initWithCustom:(NSString*)name;
@end
#import "Playlist.h"

@implementation Playlist
-(id) init{
    self = [super init];
    if(self){
        _name = @"New Player";
        _creator = @"N/A";
    }
    return self;
}

-(id) initWithCustom:(NSString*)name{
    self = [super init];
    if(self){
        _name = name;
        _creator = @"N/A";
    }
    return self;
}

-(bool) isLeaf{
    return YES;
}
@end

7、綁定圣勒。
7-1费变、將Table Column與Tree Controller進行綁定;


image.png

7-2將HEADER CELL與Table Cell View進行綁定圣贸,并設(shè)置其key path為objectvalue.name挚歧;


image.png

7-3、將Table View Cell與Table Cell View進行綁定吁峻,設(shè)置為其key path為objectvalue.name滑负。
image.png

7-4、最后將View Controller做為Outline View的Datasource與Delegate用含。
image.png

8.拖拽大法矮慕,將outline view與tree controller拖拽直ViewController.h中。


image.png

image.png

并且在ViewController.h中添加NSOutlineViewDataSource和NSOutlineViewDelegate協(xié)議耕餐。

//ViewController.h
#import <Cocoa/Cocoa.h>
@interface ViewController : NSViewController<NSOutlineViewDataSource,NSOutlineViewDelegate>
@property (weak) IBOutlet NSOutlineView *outlineView;
@property (strong) IBOutlet NSTreeController *treeController;
@end

9.在ViewController.m中添加addData方法凡傅,并在viewDidLoad中調(diào)用,實現(xiàn)outlineView的協(xié)議方法肠缔。

#import "ViewController.h"
#import "Playlist.h"
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
    [self addData];
}

//內(nèi)部方法1:初始化數(shù)據(jù)
- (void) addData{
    NSDictionary *root = @{@"name":@"Library",@"isLeaf":@NO};
    
    NSMutableArray *array =[[NSMutableArray alloc] initWithCapacity:(NSUInteger)10];
    [array addObject:[[Playlist alloc] initWithCustom:@"New Player1"]];
    [array addObject:[[Playlist alloc] initWithCustom:@"New Player2"]];
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:root];
    
    [dict setObject:array forKey:@"children"];
    
    [_treeController addObject:dict];
}

//內(nèi)部方法2:判斷是否為頭
- (bool) isHeader:(id)Item{
    Item = (NSTreeNode*)Item;
    if(Item){
        return ![[Item representedObject] isKindOfClass:[Playlist class]];
    }
    return ![Item isKindOfClass:[Playlist class]];
}

//實現(xiàn)協(xié)議方法
- (NSView *)outlineView:(NSOutlineView *)outlineView viewForTableColumn:(NSTableColumn *)tableColumn item:(id)item{
    if([self isHeader:item]){
        return [outlineView makeViewWithIdentifier:@"HeaderCell" owner:self];
    }
    return [outlineView makeViewWithIdentifier:@"DataCell" owner:self];
}

- (void)setRepresentedObject:(id)representedObject {
    [super setRepresentedObject:representedObject];

    // Update the view, if already loaded.
}
@end

10.階段一完成,效果如下哼转。


image.png

階段二 實現(xiàn)拖拽調(diào)整數(shù)據(jù)功能

1.打開ViewController.m中明未,在viewDidLoad方法中新增代碼。

    //階段二
    [_outlineView expandItem:nil expandChildren:YES];   //自動展開
    //拖拽事件相關(guān)
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    [arr addObject:NSPasteboardTypeString];
    [_outlineView registerForDraggedTypes:arr];

2.添加以下三個函數(shù)壹蔓。

//階段二之支持拖拽
- (id<NSPasteboardWriting>)outlineView:(NSOutlineView *)outlineView pasteboardWriterForItem:(id)item{
    Playlist *playlist = [item representedObject];
    if ([playlist isKindOfClass:[Playlist class]]){
        NSPasteboardItem* pbItem = [[NSPasteboardItem alloc] init];
        [pbItem setString:playlist.name forType:NSPasteboardTypeString];
        return pbItem;
    }
    return nil;
}

//階段二之判斷是否為有效拖拽
- (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id<NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index{
    bool canDrag = index>=0 && item!=nil;
    if (!canDrag){
        return NSDragOperationNone;
    }
    return NSDragOperationMove;
}

//階段二之拖拽調(diào)整位置
- (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id<NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index{
    
    NSPasteboard* pb = [info draggingPasteboard];
    NSString *name = [pb stringForType:NSPasteboardTypeString];
    NSTreeNode *sourceNode = nil;
    
    if([(NSTreeNode*)item childNodes] != nil){
        for(id node in [item childNodes]){
            Playlist * playlist = [node representedObject];
            if([playlist isKindOfClass:[Playlist class]]){
                if([playlist.name isEqualToString:name]){
                    sourceNode = node;
                }
            }
        }
    }
    if(sourceNode == nil){
        return NO;
    }
    
    NSUInteger indexs[] ={0,index};
    NSIndexPath* toIndexPath = [[NSIndexPath alloc] initWithIndexes:indexs length:2];
    [_treeController moveNode:sourceNode toIndexPath:toIndexPath];
    
    return YES;
}

3.階段二趟妥,完成!


image.png

階段三 實現(xiàn)撤銷功能

1.實現(xiàn)兩個協(xié)議方法佣蓉。

//階段三之是否為GroupItem
- (BOOL)outlineView:(NSOutlineView *)outlineView isGroupItem:(id)item{
    return [self isHeader:item];
}

//階段三之執(zhí)行撤銷動作
- (void)reverse:(NSTreeNode*)sourceNode fromIndexPath:(NSIndexPath*)fromIndexPath{
    [_treeController moveNode:sourceNode toIndexPath:fromIndexPath];
}

2.添加部分代碼至outlineView(acceptDrop)函數(shù)中披摄。

//階段二之拖拽調(diào)整位置
- (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id<NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index{
    
    NSPasteboard* pb = [info draggingPasteboard];
    NSString *name = [pb stringForType:NSPasteboardTypeString];
    NSTreeNode *sourceNode = nil;
    
    if([(NSTreeNode*)item childNodes] != nil){
        for(id node in [item childNodes]){
            Playlist * playlist = [node representedObject];
            if([playlist isKindOfClass:[Playlist class]]){
                if([playlist.name isEqualToString:name]){
                    sourceNode = node;
                }
            }
        }
    }
    if(sourceNode == nil){
        return NO;
    }
    
    //階段三之記錄原始路徑
    NSIndexPath* fromIndexPath = [_treeController selectionIndexPath];
    
    NSUInteger indexs[] ={0,index};
    NSIndexPath* toIndexPath = [[NSIndexPath alloc] initWithIndexes:indexs length:2];
    [_treeController moveNode:sourceNode toIndexPath:toIndexPath];
    
    //階段三之配置undoManager,執(zhí)行reverse動作勇凭。
    [[self.undoManager prepareWithInvocationTarget:self] reverse:sourceNode fromIndexPath:fromIndexPath];
    [self.undoManager setActionName:@"Move"];
    
    return YES;
}

3.階段三完成疚膊,效果如下。


image.png

思考

這里有個小問題虾标,在拖拽p2時寓盗,必須先點擊選中p2,再去將p2拖拽至p1,否則在撤銷時傀蚌,就會存在p2與Library位置互換的BUG基显。
這個可愛的BUG就交給你們?nèi)バ迯?fù)啦!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末善炫,一起剝皮案震驚了整個濱河市撩幽,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌箩艺,老刑警劉巖窜醉,帶你破解...
    沈念sama閱讀 221,331評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異舅桩,居然都是意外死亡酱虎,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,372評論 3 398
  • 文/潘曉璐 我一進店門擂涛,熙熙樓的掌柜王于貴愁眉苦臉地迎上來读串,“玉大人,你說我怎么就攤上這事撒妈』峙” “怎么了?”我有些...
    開封第一講書人閱讀 167,755評論 0 360
  • 文/不壞的土叔 我叫張陵狰右,是天一觀的道長杰捂。 經(jīng)常有香客問我,道長棋蚌,這世上最難降的妖魔是什么嫁佳? 我笑而不...
    開封第一講書人閱讀 59,528評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮谷暮,結(jié)果婚禮上蒿往,老公的妹妹穿的比我還像新娘。我一直安慰自己湿弦,他們只是感情好瓤漏,可當我...
    茶點故事閱讀 68,526評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著颊埃,像睡著了一般蔬充。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上班利,一...
    開封第一講書人閱讀 52,166評論 1 308
  • 那天饥漫,我揣著相機與錄音,去河邊找鬼肥败。 笑死趾浅,一個胖子當著我的面吹牛愕提,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播皿哨,決...
    沈念sama閱讀 40,768評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼浅侨,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了证膨?” 一聲冷哼從身側(cè)響起如输,我...
    開封第一講書人閱讀 39,664評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎央勒,沒想到半個月后不见,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,205評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡崔步,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,290評論 3 340
  • 正文 我和宋清朗相戀三年稳吮,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片井濒。...
    茶點故事閱讀 40,435評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡灶似,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出瑞你,到底是詐尸還是另有隱情酪惭,我是刑警寧澤,帶...
    沈念sama閱讀 36,126評論 5 349
  • 正文 年R本政府宣布者甲,位于F島的核電站春感,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏虏缸。R本人自食惡果不足惜鲫懒,卻給世界環(huán)境...
    茶點故事閱讀 41,804評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望刽辙。 院中可真熱鬧刀疙,春花似錦、人聲如沸扫倡。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,276評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽撵溃。三九已至,卻和暖如春锥累,著一層夾襖步出監(jiān)牢的瞬間缘挑,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,393評論 1 272
  • 我被黑心中介騙來泰國打工桶略, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留语淘,地道東北人诲宇。 一個月前我還...
    沈念sama閱讀 48,818評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像惶翻,于是被迫代替她去往敵國和親姑蓝。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,442評論 2 359