判断两个控件在同一个Window上是否有重叠

Posted 梦之魂_JG

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了判断两个控件在同一个Window上是否有重叠相关的知识,希望对你有一定的参考价值。

判断两个控件在同一个Window上是否有重叠

//对UIView写分类
- (BOOL)intersectWithView:(UIView *)view;

- (BOOL)intersectWithView:(UIView *)view
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    CGRect selfRect = [self convertRect:self.bounds toView:window];
    CGRect viewRect = [view convertRect:view.bounds toView:window];
    return CGRectIntersectsRect(selfRect, viewRect);
}

 

添加一个更高级别的UIWindow,目的点击状态栏时让ScrollView滚动到顶部

//.h文件
#import <Foundation/Foundation.h>

@interface JGTopWindow : NSObject
+ (void)show;
@end


//.m文件
#import "JGTopWindow.h"

@implementation JGTopWindow

static UIWindow *window_;
+ (void)show
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        window_ = [[UIWindow alloc] init];
        window_.frame = [UIApplication sharedApplication].statusBarFrame;
        // 窗口默认显示黑色
        window_.backgroundColor = [UIColor clearColor];
        // UIWindowLevelAlert > UIWindowLevelStatusBar > UIWindowLevelNormal
        // 窗口默认等级是UIWindowLevelNormal,等级最低,放在最下层,点击手势被拦截,无法被监听到
        window_.windowLevel = UIWindowLevelAlert;
        // 默认是隐藏的
        window_.hidden = NO;
        [window_ addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(topWindowClick)]];
    });
}

+ (void)topWindowClick
{
    // 主窗口
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    
    // 查找主窗口中的所有scrollView
    [self findScrollViewsInView:window];
}

/**
 *  查找view中的所有scrollView
 */
+ (void)findScrollViewsInView:(UIView *)view
{
    // 利用递归查找所有的子控件
    for (UIView *subview in view.subviews) {
        [self findScrollViewsInView:subview];
    }
    
    
    if (![view isKindOfClass:[UIScrollView class]]) return;
    
    // 判断是否跟window有重叠
    if (![view intersectWithView:[UIApplication sharedApplication].keyWindow]) return;
    //    CGRect windowRect = [UIApplication sharedApplication].keyWindow.bounds;
    //    CGRect viewRect = [view convertRect:view.bounds toView:nil];
    //    // 跟window不重叠
    //    if (!CGRectIntersectsRect(windowRect, viewRect)) return;
    
    // 如果是scrollView
    UIScrollView *scrollView = (UIScrollView *)view;

    // 修改offset
    CGPoint offset = scrollView.contentOffset;
    offset.y = - scrollView.contentInset.top;
    [scrollView setContentOffset:offset animated:YES];
    
    // [scrollView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
}
@end

 

以上是关于判断两个控件在同一个Window上是否有重叠的主要内容,如果未能解决你的问题,请参考以下文章

怎样判断平面上一个矩形和一个圆形是否有重叠

如何使控件扩展通过控件绑定或与其他控件重叠?

perf 对两个map是否重叠的判断,以及函数map_groups__fixup_overlappings代码逻辑

判断两个区间是否重叠图解

WPF中如何让一个元素与另一个元素重叠?

SQL判断两个时间段是否重叠