标签:
利用UIWindow实现快速到达顶部
如下图,在状态栏添加一个没有颜色的UIWindow(里面添加一个按钮),实现点击这个按钮时能快速的回到当前界面的顶部
核心代码
一、利用UIWindow实现到达顶部
1、创建一个新的窗口
1)UIWindow的级别,级别越高,越显示在上层(级别高的window盖在级别低的window上面)
UIWindowLevelNormal < UIWindowLevelStatusBar < UIWindowLevelAlert
@interface AppDelegate () @property (nonatomic, strong) UIWindow *topWindow; @end @implementation AppDelegate - (UIWindow *)topWindow{ if (_topWindow == nil) { _topWindow = [[UIWindow alloc] init]; _topWindow.windowLevel = UIWindowLevelAlert; _topWindow.frame = CGRectMake(0, 0, CHGScreenW, 20); _topWindow.backgroundColor = [UIColor clearColor]; // 这句很重要,默认是隐藏的,要想显示必须手动设置为NO _topWindow.hidden = NO; [_topWindow addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(topWindowClick)]]; } return _topWindow; }
2、遍历每一个窗口
- (void)topWindowClick { NSArray *windows = [UIApplication sharedApplication].windows; for (UIWindow *window in windows) {
// 遍历该窗口下所有子控件 [self searchSubviews:window]; } }
3、遍历该窗口下所有子控件
/** * 搜索superview内部的所有子控件 */ - (void)searchSubviews:(UIView *)superview { for (UIScrollView *scrollView in superview.subviews) { [self searchSubviews:scrollView]; // 判断是否为 scrollView if (![scrollView isKindOfClass:[UIScrollView class]]) continue; // 判断scrollView是否在窗口上 (是否相交) // 计算出scrollView在window坐标系上的矩形框 CGRect scrollViewRect = [scrollView convertRect:scrollView.bounds toView:scrollView.window]; CGRect windowRect = scrollView.window.bounds; // 判断scrollView的边框是否和window的边框交叉 if (!CGRectIntersectsRect(scrollViewRect, windowRect)) continue; // 能来到这里说明scrollView在窗口上,修改偏移量,滚到最顶部 CGPoint offset = scrollView.contentOffset; offset.y = - scrollView.contentInset.top; [scrollView setContentOffset:offset animated:YES]; } }
4、程序激活时主动调用懒加载
// 程序激活的时候调用topWindow - (void)applicationDidBecomeActive:(UIApplication *)application { [self topWindow]; }
标签:
原文地址:http://www.cnblogs.com/chglog/p/4829700.html