1、檢測(cè)view在特定前提下是否可見
簡(jiǎn)短的代碼很難檢測(cè)當(dāng)前視圖是否在屏幕上可見,因?yàn)榇嬖诒恍值芤晥D或者父視圖被叔輩視圖完全遮擋的情況,其實(shí)也沒(méi)有必要寫大量的代碼去實(shí)現(xiàn)通用的邏輯,在大前提下能判斷時(shí),針對(duì)特定情況在添加少量代碼即可實(shí)現(xiàn)最終目的,效率自然也是最高的。
UIView的window屬性為nil的幾種情況
- 父視圖為nil
- 父視圖的父視圖為nil,以及父父父父...視圖(非主窗口)為nil
- 離開導(dǎo)航棧頂
- 非tabBarController的選中視圖
@implementation UIView (CheckVisible)
+ (BOOL)_checkVisible:(UIView *)view inView:(UIView *)inView
{
if(!inView){
return YES;
}
CGRect frameInView = view.frame;
if(inView!=view.superview){
frameInView = [inView convertRect:view.frame fromView:view.superview];
}
if(CGRectIntersectsRect(frameInView, inView.bounds))
{
return [self _checkVisible:view inView:inView.superview];
}
return NO;
}
- (BOOL)checkVisibleOnScreen
{
if(self.hidden){
return NO;
}
if(!self.window){
return NO;
}
if(!self.superview){
return NO;
}
return [UIView _checkVisible:self inView:self.superview];
}
@end
CGRectIntersectsRect 檢測(cè)兩個(gè)rect是否相交
https://developer.apple.com/documentation/coregraphics/1454747-cgrectintersectsrect