RATreeNodeCollectionController.m 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. //The MIT License (MIT)
  2. //
  3. //Copyright (c) 2013 Rafał Augustyniak
  4. //
  5. //Permission is hereby granted, free of charge, to any person obtaining a copy of
  6. //this software and associated documentation files (the "Software"), to deal in
  7. //the Software without restriction, including without limitation the rights to
  8. //use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  9. //the Software, and to permit persons to whom the Software is furnished to do so,
  10. //subject to the following conditions:
  11. //
  12. //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  14. //FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  15. //COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  16. //IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  17. //CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  18. //
  19. #import "RATreeNodeCollectionController.h"
  20. #import "RATreeNode.h"
  21. @implementation RATreeNodeCollectionController
  22. - (id)init
  23. {
  24. self = [super init];
  25. if (self) {
  26. self.root = [[RATreeNode alloc] initWithItem:nil parent:nil expanded:YES];
  27. }
  28. return self;
  29. }
  30. - (void)addTreeNode:(RATreeNode *)treeNode
  31. {
  32. if (treeNode.parent == nil) {
  33. [self.root addChildNode:treeNode];
  34. treeNode.parent = self.root;
  35. } else {
  36. [treeNode.parent addChildNode:treeNode];
  37. if (treeNode.expanded) {
  38. [treeNode expand];
  39. }
  40. }
  41. }
  42. - (RATreeNode *)treeNodeForIndex:(NSInteger)index
  43. {
  44. if (index < 0) {
  45. return nil;
  46. }
  47. return [self treeNodeForIndex:index treeNode:self.root];
  48. }
  49. - (RATreeNode *)treeNodeForIndex:(NSInteger)index treeNode:(RATreeNode *)currentTreeNode
  50. {
  51. for (RATreeNode *treeNode in currentTreeNode.children) {
  52. if ([treeNode startIndex] == index) {
  53. return treeNode;
  54. } else if (index <= [treeNode endIndex]) {
  55. return [self treeNodeForIndex:index treeNode:treeNode];
  56. }
  57. }
  58. return nil;
  59. }
  60. - (NSInteger)indexForItem:(id)item
  61. {
  62. return [self indexForItem:item treeNode:self.root];
  63. }
  64. - (NSInteger)indexForItem:(id)item treeNode:(RATreeNode *)currentTreeNode
  65. {
  66. NSArray *array = [self.root visibleDescendants];
  67. NSInteger index = 0;
  68. for (RATreeNode *treeNode in array) {
  69. if ([treeNode.item isEqual:item]) {
  70. return index;
  71. }
  72. index++;
  73. }
  74. return -1;
  75. }
  76. @end