2011-09-09 4 views
4

화면에 UIView가 여러 개 있습니다. 특정 뷰 (참조 할 수있는 뷰)가 다른 뷰와 교차하는지 확인하는 방법은 무엇이 최선인지 알고 싶습니다. 내가 지금하고있는 방식은 모든 하위 뷰를 반복하고 하나씩 프레임 사이에 교차가 있는지 확인합니다.UIView가 다른 UIView와 교차하는지 확인

매우 효율적으로 보이지 않습니다. 이 작업을 수행하는 더 좋은 방법이 있습니까?

+1

Instruments에서 코드를 실행 해 보셨습니까? 나는 그것이 완벽하고 빠르고 효율적이라는 것을 알게 될 것입니다. rect 교차에 대한 코드는 단순한 수학이므로 속도면에서 문제가되는 것을 볼 수 없으며 수 백 건의 조회도 있습니다. –

답변

0

먼저 모든 UIView의 프레임과 관련 참조를 저장하는 배열을 만듭니다.

잠재적으로 백그라운드 스레드에서 배열의 내용을 사용하여 충돌 테스트를 실행할 수 있습니다. 사각형에 대한 간단한 충돌 테스트의 경우 다음 질문을 확인하십시오. Simple Collision Algorithm for Rectangles

희망 하시겠습니까?

34

CGRectIntersectsRect라는 함수가 두 개의 CGRect를 인수로 받고 두 개의 rect가 교차하는 경우를 반환합니다. 그리고 UIView에는 UIView 객체의 NSArray 인 subviews 속성이 있습니다.

- (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 { \t (containerView.subviews에서의 UIView * theView)에 대해 { 가 \t \t이 경우 ([selectedView ISEQUAL : theView]) \t \t \t 계속 ; \t \t \t \t 경우 (CGRectIntersectsRect (selectedView.frame, theView.frame)) { \t \t \t 창 YES; \t \t} } \t return NO; } – Jonny

+1

주석에 코드 서식을 가져올 수 없습니다. :-P 어쨌든 약간의 리팩터링 + 코드 수정. – Jonny

+0

자네가 맞아. 나는 반복을 떠나야 해. 그래서 코드를보다 효율적으로 변경했습니다. –

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

더 신속한 접근 방식은'CGHectIntersectsRect (viewToCheck.frame, viewS.frame)'을'viewToCheck.frame.intersects (viewS.frame)' – kabiroberai

+0

으로 바꾼 것입니다. 신속하게 3, 친절하게 사용 view.frame.intersects (secondView.frame) {...} – aznelite89

관련 문제