若當前的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