实现tableView回到顶部的代码
#import <Foundation/Foundation.h>
@interface XMGTopWindow : NSObject
+ (void)show;
+ (void)hide;
@end
#import "XMGTopWindow.h"
@implementation XMGTopWindow
static UIWindow *window_;
+ (void)initialize{
window_ = [[UIWindow alloc] init];
window_.frame = CGRectMake(0, 0, XQMScreenW, 20);
window_.windowLevel = UIWindowLevelAlert;
window_.backgroundColor = [UIColor clearColor];
[window_ addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(windowClick)]];
}
+ (void)show{
window_.hidden = NO;
}
+ (void)hide{
window_.hidden = YES;
}
/**
* 监听窗口点击
*/
+ (void)windowClick{
UIWindow *window = [UIApplication sharedApplication].keyWindow;
[self searchScrollViewInView:window];
}
+ (void)searchScrollViewInView:(UIView *)superview{
for (UIScrollView *subview in superview.subviews) {
// 如果是scrollview, 滚动最顶部
if ([subview isKindOfClass:[UIScrollView class]] && subview.isShowingOnKeyWindow) {
CGPoint offset = subview.contentOffset;
offset.y = - subview.contentInset.top;
[subview setContentOffset:offset animated:YES];
}
// 继续查找子控件
[self searchScrollViewInView:subview];
}
}
@end
上面使用 [subview setContentOffset:offset animated:YES];
滚动到顶部,如果出现tableView滚动了一部分后停留(特别是在加载更多数据 reloadData
之后),使用下面方法
if([subview isKindOfClass:[UITabelView class]]){
UITableView *tableView = (UITableView *)subview;
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}else{
CGPoint offset = subview.contentOffset;
offset.y = - subview.contentInset.top;
[subview setContentOffset:offset animated:YES];
}
判断视图是否显示在屏幕中
- (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;
}
网友评论