2011-09-16 44 views
0

如果我有一个包含10个子视图的NSView,并且拖动其中一个子视图,那么确定剩下的哪些视图关闭到拖动的视图最简单的方法是什么?我的代码正在工作,但我不知何故觉得我在用扳手来调整小提琴。有没有更优雅的方式?Objective-C:获取最近的NSView拖动NSView

子视图是该视图的父视图的子视图的阵列(因此它包括这个视图中)
的子视图的工具提示包含他们的页面#格式化像“Page_#”

- (void) mouseUp: (NSEvent*) e { 

    //set up a ridiclous # for current distance 
    float mtDistance = 12000000.0; 

    //get this page number 
    selfPageNum = [[[self toolTip] substringFromIndex:5] intValue]; 

    //set up pageViews array 
    pageViews = [[NSMutableArray alloc] init]; 

    //loop through the subviews 
    for (int i=0; i<[subviews count]; i++) { 

      //set up the view 
      thisView = [subviews objectAtIndex:i]; 

      //filter for view classes 
      NSString* thisViewClass = [NSString stringWithFormat:@"%@", [thisView className]]; 
      if ([thisViewClass isEqual:@"Page"]) { 

        //add to the pageViews array 
        [pageViews addObject:thisView]; 

        if (self != thisView) { 
          //get the view and self frame 
          NSRect movedViewFrame = [self frame]; 
          NSRect thisViewFrame = [thisView frame]; 

          //get the location area (x*y) 
          float movedViewLoc = movedViewFrame.origin.x * (movedViewFrame.origin.y * -1); 
          float thisViewLoc = thisViewFrame.origin.x * (thisViewFrame.origin.y * -1); 

          //get the difference between x locations 
          float mtDifference = movedViewLoc - thisViewLoc; 
          if (mtDifference < 0) { 
            mtDifference = mtDifference * -1; 
          } 

          if (mtDifference < mtDistance) { 
            mtDistance = mtDifference; 
            closesView = thisView; 
          } 
        } 

      }//end class check 
     }//end loop 

//....more stuff 

} 

回答

2

http://en.wikipedia.org/wiki/Distance

distance formula

sqrt(pow((x2 - x1), 2) + pow((y2 - y1), 2))) 

编辑:既然你只需要找到笑rtest距离,而不是确切的距离,你不需要采取平方根。感谢您的见解Abizern

pow((x2 - x1), 2) + pow((y2 - y1), 2) 
+1

距离的标准答案。但是,当比较距离时,不需要浪费计算平方根的周期。如果d1 Abizern