点击状态栏回到顶部两种实现

1.局部设置

scrollView有个属性scrollsToTop,默认值为YES. 所以默认情况下点击状态栏就可以回到顶部。但当一个控制器中有多个scrollView或其子类时,因为默认值都是YES,所以系统不知道要让哪个scrollView回到顶部。所以要让需要回到顶部的scrollView.scrollsToTop = YES,而其他的scrollView的设置成NO.

 

2.全局设置

新建一个window,windowLevel为alert的,背景色为clear,加一个手势,设置点击事件。

注意,iOS9之后,每个window都要设置一个rootViewController

一个范例:

 1 @implementation TopWindow
 2 
 3 static UIWindow *window_;
 4 
 5 + (void)initialize
 6 {
 7     window_ = [[UIWindow alloc] init];
 8     window_.backgroundColor = [UIColor clearColor];
 9     window_.frame = CGRectMake(0, 0, XMGScreenW, 20);
10     window_.windowLevel = UIWindowLevelAlert;
11     [window_ addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(windowClick)]];
12     UIViewController *vc = [[UIViewController alloc]init];
13     
14     vc.view.backgroundColor = [UIColor clearColor];
15     window_.rootViewController = vc;
16 }
17 
18 + (void)show
19 {
20     window_.hidden = NO;
21 }
22 
23 + (void)hide
24 {
25     window_.hidden = YES;
26 }
27 
28 /**
29  * 监听窗口点击
30  */
31 + (void)windowClick
32 {
33     UIWindow *window = [UIApplication sharedApplication].keyWindow;
34     [self searchScrollViewInView:window];
35 }
36 
37 + (void)searchScrollViewInView:(UIView *)superview
38 {
39     for (UIScrollView *subview in superview.subviews) {
40         // 如果是scrollview, 滚动最顶部
41         if ([subview isKindOfClass:[UIScrollView class]] && subview.isShowingOnKeyWindow) {
42             CGPoint offset = subview.contentOffset;
43             offset.y = - subview.contentInset.top;
44             [subview setContentOffset:offset animated:YES];
45         }
46         
47         // 继续查找子控件
48         [self searchScrollViewInView:subview];
49     }
50 }
51 @end


//UIView的一个分类方法

- (BOOL)isShowingOnKeyWindow


{


    // 主窗口

    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;

// 以主窗口左上角为坐标原点, 计算self的矩形框
CGRect newFrame = [keyWindow convertRect:self.frame fromView:self.superview];

 CGRect winBounds = keyWindow.bounds;

  // 主窗口的bounds 和 self的矩形框 是否有重叠


    BOOL intersects = CGRectIntersectsRect(newFrame, winBounds);

 return !self.isHidden && self.alpha > 0.01 && self.window == keyWindow && intersects;

}


 

 

 

posted @ 2015-06-07 19:44  Emyin  阅读(1008)  评论(0编辑  收藏  举报