轉載 請注明出處:ALDRIDGE1的專欄
頭文件:
/***************************************************** * MIT Licence * * Author: __承_影__ * * Date: 2015.2.10 * ****************************************************/ @interface UIView (UIScreenDisplaying) // 判斷View是否顯示在屏幕上 - (BOOL)isDisplayedInScreen; @end
/***************************************************** * MIT Licence * * Author: __承_影__ * * Date: 2015.2.10 * ****************************************************/ @implementation UIView (UIScreenDisplaying) // 判斷View是否顯示在屏幕上 - (BOOL)isDisplayedInScreen { if (self == nil) { return FALSE; } CGRect screenRect = [UIScreen mainScreen].bounds; // 轉換view對應window的Rect CGRect rect = [self convertRect:self.frame fromView:nil]; if (CGRectIsEmpty(rect) || CGRectIsNull(rect)) { return FALSE; } // 若view 隱藏 if (self.hidden) { return FALSE; } // 若沒有superview if (self.superview == nil) { return FALSE; } // 若size為CGrectZero if (CGSizeEqualToSize(rect.size, CGSizeZero)) { return FALSE; } // 獲取 該view與window 交叉的 Rect CGRect intersectionRect = CGRectIntersection(rect, screenRect); if (CGRectIsEmpty(intersectionRect) || CGRectIsNull(intersectionRect)) { return FALSE; } return TRUE; }
測試用例:
UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)]; // 無父視圖 BOOL b1 = [v isDisplayedInScreen]; NSLog(@"b1: %d", b1); // [self.view addSubview:v]; BOOL b2 = [v isDisplayedInScreen]; NSLog(@"b2: %d", b2); v.frame = CGRectZero; BOOL b3 = [v isDisplayedInScreen]; NSLog(@"b3: %d", b3); CGRect screenRect = [UIScreen mainScreen].bounds; CGFloat screenWidth = screenRect.size.width; CGFloat screenHeight = screenRect.size.height; v.frame = CGRectMake(-screenWidth, -screenHeight, screenWidth, screenHeight); BOOL b4 = [v isDisplayedInScreen]; NSLog(@"b4: %d", b4);