若当前的ViewController中只有一个scrollView,点击状态栏,该scrollView就会滚动到顶部。但当ViewController中有多个scrollView时,就不灵了!这个时候,怎么去兼容呢?
UIScrollView有这么一个属性scrollsToTop。按住command,点击scrollsToTop进去你会看到关于这个属性的注解
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.
现在知道为什么不灵了吧!!!
最近做项目,由于一个横屏的scrollView里面放置了多个tableView,但点击状态栏仍要求tableView滚动到顶部,所以要克服这个问题!
虽然"魏则西事件"让我们大家很鄙视百度,但在谷歌还进不来的情况下,我默默的百度了一下!
。。。。。。。。。。。。。。。。。。。。。。。。
问题解决后,我总结了一下。
思路是这样的:
1 追踪UIStatusBar的touch事件,然后响应该事件。不要直接向statusBar添加事件,因为并没有什么卵用!我也不知道为什么没有什么卵有!
2 找到UIApplication的keyWindow,遍历keyWindow的所有子控件。如果是scrollView,而且显示在当前keyWindow,那么将其contentOffset的y值设置为原始值(0)。这里会用到递归去进行遍历。
首先我们追踪UIStatusBar的触摸事件,需要在AppDelegate里面加入以下代码
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesBegan:touches withEvent:event]; CGPoint location = [[[event allTouches] anyObject] locationInView:self.window]; CGRect statusBarFrame = [UIApplication sharedApplication].statusBarFrame; if (CGRectContainsPoint(statusBarFrame, location)) { [self statusBarTouchedAction]; } }
然后在statusBarTouchedAction方法中将显示在当前keyWindow里面的scrollView滚动到顶部
- (void)statusBarTouchedAction { [JMSUIScrollViewTool scrollViewScrollToTop]; }
下面来看JMSUIScrollViewTool
#import <Foundation/Foundation.h> @interface JMSUIScrollViewTool : NSObject + (void)scrollViewScrollToTop; @end
#import "JMSUIScrollViewTool.h" @implementation JMSUIScrollViewTool + (void)scrollViewScrollToTop { UIWindow *window = [UIApplication sharedApplication].keyWindow; [self searchScrollViewInView:window]; } + (void)statusBarWindowClick { UIWindow *window = [UIApplication sharedApplication].keyWindow; [self searchScrollViewInView:window]; } + (BOOL)isShowingOnKeyWindow:(UIView *)view { UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow; CGRect newFrame = [keyWindow convertRect:view.frame fromView:view.superview]; CGRect winBounds = keyWindow.bounds; BOOL intersects = CGRectIntersectsRect(newFrame, winBounds); return !view.isHidden && view.alpha > 0.01 && view.window == keyWindow && intersects; } + (void)searchScrollViewInView:(UIView *)supView { for (UIScrollView *subView in supView.subviews) { if ([subView isKindOfClass:[UIScrollView class]] && [self isShowingOnKeyWindow:supView]) { CGPoint offset = subView.contentOffset; offset.y = -subView.contentInset.top; [subView setContentOffset:offset animated:YES]; } [self searchScrollViewInView:subView]; } } @end
接下来,就让你的项目跑起来吧!
此处应有掌声。。。
参考:http://stackoverflow.com/questions/3753097/how-to-detect-touches-in-status-bar
http://www.cocoachina.com/ios/20150807/12949.html