iOS判断UIView是否显示在屏幕上
转载 请注明出处: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);
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。