2011-09-16 7 views
0

NSViewに10個のサブビューがあり、サブビューの1つをドラッグすると、残りのビューのどれがドラッグされたビューを閉じるのが最も簡単ですか?私のコードは動作していますが、私は何とか私がヴァイオリンを微調整するためにサルのレンチを使用していると感じています。よりエレガントな方法がありますか?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))) 

編集:あなただけの笙を見つける必要があるので、正確な距離ではなく、平方根をとる必要はありません。洞察をお寄せいただきありがとうございます。

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

距離に関する標準的な回答です。しかし、距離を比較する場合、平方根を計算する際にサイクルを無駄にする必要はありません。 d1 Abizern

関連する問題