epreston/PSTreeGraph — Issue #17: Fun with tap gesture: collapse / expand tree
Author: jolo2000
Created: 2012-01-03 12:10:07+00:00
State: open

Hi,

this is just a little hack to get a collapsing or expanding tree with a double tap gesture.
Thanks to the excellent design of PSTreeGraph, this feature is easy to realize.

First implement the tap gesture recognizer:

- (void) initTapGestureRecognition {
UITapGestureRecognizer *tapDoubleGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
tapDoubleGesture.numberOfTapsRequired = 2;
[self addGestureRecognizer:tapDoubleGesture];
[tapDoubleGesture release];
}

With a double tap on the view, the "handleDoubleTap" function is called:

-(void)handleDoubleTap:(UITapGestureRecognizer*)gestureRecognizer {

if (gestureRecognizer.state == UIGestureRecognizerStateEnded)
{
NSLog(@"See a tap double gesture");
ruleOutsTreeView = [gestureRecognizer view];
if (isCollapsed) {
[ruleOutsTreeView expandRoot];
isCollapsed = false;
}
else if (!isCollapsed) {
[ruleOutsTreeView collapseRoot];
isCollapsed = true;
}
}
}

"isCollapsed" is just a local, private variable, which holds the state of the tree.
"ruleOutsTreeView" represents the "PSBaseTreeGraphView".

You can register the tap gesture recognizer in your custom tree view class, e.g. PSHTreeGraphView

- (id) initWithCoder:(NSCoder *)decoder
{
self = [super initWithCoder:decoder];
if (self) {

// Initialization code when loaded from XIB (this example)
// init gesture recognizer
[self initTapGestureRecognition];
bool isCollapsed = false;
}
return self;
}

To get the tree collapsed or expanded, I modified the functions "expandRoot()" and "collapseRoot()" of PSBaseTreeGraphView.m
E.g.:

- (void) collapseRoot
{
[UIView beginAnimations:@"TreeNodeExpansion" context:nil];
[UIView setAnimationDuration:2.0];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[[self rootSubtreeView] setExpanded:NO];
[[[self rootSubtreeView] enclosingTreeGraph] layoutGraphIfNeeded];

[UIView commitAnimations];
}

- (void) expandRoot
{
[UIView beginAnimations:@"TreeNodeExpansion" context:nil];
[UIView setAnimationDuration:2.0];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[[self rootSubtreeView] setExpanded:NO]; // if not set, a collapsed subtree node will not expand
[[self rootSubtreeView] setExpanded:YES];
[[[self rootSubtreeView] enclosingTreeGraph] layoutGraphIfNeeded];

[UIView commitAnimations];

}

That's all, now you have a tree collapsing or expanding with a double tap.

Have fun
Johannes