iOS判断UIView是否显示在屏幕上
Posted wjwdive
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS判断UIView是否显示在屏幕上相关的知识,希望对你有一定的参考价值。
@interface
- (BOOL)isDisplayedInScreen;
@end
@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;
}
retrun true;
}
@end
//test case
UIView *view = [UIView alloc] initWithFrame:CGRectMake(0,0,40,40)];
//无父视图
BOOL b1 = [view isDisplayedInScreen];
NSLog(@"b1: %d", b1);
[self.view addSubView:view];
BOOL b2 = [view isDisplayedInScreen];
NSLog(@"b2:%d",b2);
v.frame = CGRectZero;
BOOL b3 = [view isDisplayedSceen];
NSLog("b3:%d",b3);
CGRect screenRect = [UIScreen mainScreen].bounds;
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
view.frame = CGRectMake(-screenWidth, -screenHeight, screenWidth, screenHeight);
BOOL b4 = [view isDisplayedInscreen];
NSLog(@"b4:%d",b4);
以上是关于iOS判断UIView是否显示在屏幕上的主要内容,如果未能解决你的问题,请参考以下文章
如何在 iOS 屏幕上点击某个区域时隐藏 UIView 并使其显示