美文网首页iOS开发新发现
【功能实现】实现点击状态栏tableView滚到顶部

【功能实现】实现点击状态栏tableView滚到顶部

作者: 小子爱搞事 | 来源:发表于2016-11-24 17:20 被阅读9次
    实现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;
    
    }
    
    

    相关文章

      网友评论

        本文标题:【功能实现】实现点击状态栏tableView滚到顶部

        本文链接:https://www.haomeiwen.com/subject/niobpttx.html