2011-09-09 6 views
4

私はUIViewsを画面に表示しています。私は、特定のビュー(私が参照している)が他のビューと交差しているかどうかをチェックする方法が何であるかを知りたい。私が今やっているやり方は、フレーム間に交差点があるかどうかをすべてのサブビューで確認し、1つずつチェックすることです。UIViewが他のUIViewと交差しているかどうかを検出

これはあまり効率的ではないようです。これを行うより良い方法はありますか?

+1

Instrumentsでコードを実行しようとしましたか?私はあなたがそれが完全に速くて効率的だと思うでしょう。直交点のコードは単純な数学なので、数百ものビューであっても、速度の面では問題ではありません。 –

答えて

0

まず、すべてのUIViewのフレームとそれに関連付けられた参照を格納する配列を作成します。

潜在的にバックグラウンドスレッドでは、配列の内容を使用していくつかの衝突テストを実行できます。矩形のみの単純な衝突テストでは、このSOの質問をチェックしてください:Simple Collision Algorithm for Rectangles

34

CGRectIntersectsRectという関数があります。この関数は引数として2つのCGRectを受け取り、指定された2つの矩形が交差するかどうかを返します。 UIViewには、UIViewオブジェクトのNSArrayであるサブビュープロパティがあります。

- (BOOL)viewIntersectsWithAnotherView:(UIView*)selectedView { 

    NSArray *subViewsInView = [self.view subviews];// I assume self is a subclass 
             // of UIViewController but the view can be 
             //any UIView that'd act as a container 
             //for all other views. 

    for(UIView *theView in subViewsInView) { 

     if (![selectedView isEqual:theView]) 
      if(CGRectIntersectsRect(selectedView.frame, theView.frame)) 
       return YES; 
    } 

    return NO; 
} 
+1

+(BOOL)viewIntersectsWithAnotherView:(UIViewの*)selectedView用のInView:(UIViewの*)containerView {(containerView.subviewsでのUIView * theView)用 \t { \t \t([selectedViewのisEqual:theView])場合 \t \t \tを続行; \t \t \t \t YES(CGRectIntersectsRect(selectedView.frame、theView.frame)){ \t \t \t戻った場合。 \t \t} } \t return NO; } – Jonny

+1

コメントにコードの書式を設定できませんでした。 :-Pとにかく少しのリファクタリング+コード修正。 – Jonny

+0

あなたは正しいジョニーです。私は反復を残すべきです。だから私はコードをより効率的に変更しました。 –

2

はその後、ここに受け入れ答えどおりに迅速で同じことを達成することである。だから、2つの矩形が交差する場合などのように、この配列を反復処理し、確認しますBOOL戻り値を持つメソッドを書くことができます関数。 Readymadeコード。ステップごとにコピーして使用してください。ところで、Swift 2.1.1でXcode 7.2を使用しています。

func checkViewIsInterSecting(viewToCheck: UIView) -> Bool{ 
    let allSubViews = self.view!.subviews //Creating an array of all the subviews present in the superview. 
    for viewS in allSubViews{ //Running the loop through the subviews array 
     if (!(viewToCheck .isEqual(viewS))){ //Checking the view is equal to view to check or not 
      if(CGRectIntersectsRect(viewToCheck.frame, viewS.frame)){ //Checking the view is intersecting with other or not 
       return true //If intersected then return true 
      } 
     } 
    } 
    return false //If not intersected then return false 
} 

この関数を呼び出し、次のとおり -

let viewInterSected = self.checkViewIsInterSecting(newTwoPersonTable) //It will give the bool value as true/false. Now use this as per your need 

感謝。

これが役に立った。

+1

より速いアプローチは、 'viewToCheck.frame.intersects(viewS.frame) 'で' CGRectIntersectsRect(viewToCheck.frame、viewS.frame) 'を置き換えることです。 – kabiroberai

+0

迅速に3、親切に使用view.frame.intersects(secondView.frame){...} – aznelite89

関連する問題