iOS开发好文ios 知识小集将来跳槽用

iOS-点击状态栏自动回到顶部功能实现详解

2016-07-17  本文已影响4619人  鲲鹏DP

状态栏(statusBar)点击自动回到顶部效果,旨在为用户在浏览界面时提供便利,点击状态栏能够快速回到界面顶部,所以主要针对可以滚动的UIScrollView和其子类UITableVIew和UICollectionView。这里将从以下几个方面实现该功能。


1.苹果自带功能

分析:

When the user taps the status bar, the scroll view beneath the touch which is closest to the status bar will be scrolled to top, but only if its `scrollsToTop` property is YES, its delegate does not return NO from `shouldScrollViewScrollToTop`, and it is not already at the top.
On iPhone, we execute this gesture only if there's one on-screen scroll view with `scrollsToTop` == YES. If more than one is found, none will be scrolled.

小结:

从上面分析我们可以得出结论:我们必须保证窗口上scrollsToTop == YES的ScrollView(及其子类)同一时间内有且只有一个。这一样才能保证点击statusBar,该唯一存在的ScrollView能自动回到顶部。


如何保证苹果自带的该功能一直好使呢?

解决办法:我们希望回到顶部的ScrollView的scrollsToTop =YES,其他scrollsToTop = NO。

1.让最下面的scrollView,scrollsToTop =NO。其他TableView都是该scrollView的子类。
2.遍历判断
  // 控制scrollView的scrollsToTop属性
    for (NSInteger i = 0; i < self.childViewControllers.count; i++) {
        UIViewController *childVc = self.childViewControllers[i];
        
        // 如果控制器的view没有被创建,跳过
        if (!childVc.isViewLoaded) continue;
        
        // 如果控制器的view不是scrollView,就跳过
        if (![childVc.view isKindOfClass:[UIScrollView class]]) continue;
        
        // 如果控制器的view是scrollView
        UIScrollView *scrollView = (UIScrollView *)childVc.view;
        scrollView.scrollsToTop = (i == index);
    }


2.自己实现

在statusBar的区域添加一个遮盖,监听遮盖的点击事件。

UIView

Snip20160717_14.png

UIWindow


    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        UIWindow * coverWindow =[[UIWindow alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 20)];
        self.coverWindow = coverWindow;
        coverWindow.hidden = NO;
        coverWindow.backgroundColor = [UIColor redColor];
        coverWindow.windowLevel = UIWindowLevelAlert;
        //添加手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(coverWindowClick)];
        [self.coverWindow addGestureRecognizer:tap];
    });

- (void)coverWindowClick {
   [UIView animateWithDuration:0.5 animations:^{
       
       self.tableView.contentOffset =  CGPointMake(0, 0);
   }];
}

AppDelegate中直接监听statusBar的点击

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event  {
     if ([touches.anyObject locationInView:nil].y > 20) return;
    [[NSNotificationCenter defaultCenter]postNotificationName:@"click" object:nil];
    
}
- (void)coverWindowClick {
   [UIView animateWithDuration:0.5 animations:^{
       
       self.tableView.contentOffset =  CGPointMake(0, 0);
   }];
}
上一篇 下一篇

猜你喜欢

热点阅读