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);

 

posted @ 2017-11-09 15:59  wjwdive  阅读(9277)  评论(0编辑  收藏  举报