当前UIScrollView滚动到顶
2016-04-28 本文已影响526人
HeavenWong
实现步骤:(前提是使用纯代码实现Navigation和tabBarController)
- 创建类
- .h文件
#import <Foundation/Foundation.h>
@interface TopWindow : NSObject
+ (void)show;
@end
- .m文件
#import "TopWindow.h"
@implementation TopWindow
static UIWindow *window_;
+ (void)show
{
// UIWindowLevelAlert > UIWindowLevelStatusBar > UIWindowLevelNormal
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
window_ = [[UIWindow alloc] init];
window_.frame = [UIApplication sharedApplication].statusBarFrame;
window_.backgroundColor = [UIColor clearColor];
window_.windowLevel = UIWindowLevelAlert;
window_.hidden = NO;
[window_ addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(topWindowClick)]];
});
}
+ (void)topWindowClick
{
// 主窗口
UIWindow *window = [UIApplication sharedApplication].keyWindow;
// 查找主窗口中的所有scrollView
[self findScrollViewsInView:window];
}
/**
* 查找view中的所有scrollView
*/
+ (void)findScrollViewsInView:(UIView *)view
{
// 利用递归查找所有的子控件
for (UIView *subview in view.subviews) {
[self findScrollViewsInView:subview];
}
// 如果不是scrollView
if (![view isKindOfClass:[UIScrollView class]]) return;
// 判断是否跟window有重叠
if (![view intersectWithView:[UIApplication sharedApplication].keyWindow]) return;
// CGRect windowRect = [UIApplication sharedApplication].keyWindow.bounds;
// CGRect viewRect = [view convertRect:view.bounds toView:nil];
// // 跟window不重叠
// if (!CGRectIntersectsRect(windowRect, viewRect)) return;
// 如果是scrollView
UIScrollView *scrollView = (UIScrollView *)view;
// 修改offset
CGPoint offset = scrollView.contentOffset;
offset.y = - scrollView.contentInset.top;
[scrollView setContentOffset:offset animated:YES];
// [scrollView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
}
@end
- 2.在AppDelegate.m遵守协议
UITabBarControllerDelegate - 3.创建属性
/** 记录上一次选中的子控制器的索引 */
@property (nonatomic, assign) NSUInteger lastSelectedIndex; - 4.实现方法
NSString * const WMTabBarButtonDidRepeatClickNotification = @"WMTabBarButtonDidRepeatClickNotification";
#pragma mark - <UITabBarControllerDelegate>
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
if (tabBarController.selectedIndex == self.lastSelectedIndex) { // 重复点击了同一个TabBar按钮
// 发出通知
[[NSNotificationCenter defaultCenter] postNotificationName:XMGTabBarButtonDidRepeatClickNotification object:nil];
}
// 记录目前选中的索引
self.lastSelectedIndex = tabBarController.selectedIndex;
}
- 3.在AppDelegate.m调用方法
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 添加一个最高级别的顶层window
[WMTopWindow show];
return YES;
}