你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS判斷UIView是否顯示在屏幕上

iOS判斷UIView是否顯示在屏幕上

編輯:IOS開發綜合

轉載 請注明出處: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);



  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved