iOS 滚动到顶部~demo

来源:互联网 发布:贵州省数据统计局 编辑:程序博客网 时间:2024/06/05 11:52

//联系人:石虎  QQ: 1224614774昵称:嗡嘛呢叭咪哄


/**

 1.此方法很简单,有操作视图和方法,动画效果参考

  2. 图片下面有

  3.GIF 图请看简书:  http://www.jianshu.com/p/9b48b91c3dd6


 */


#import "ViewController.h"


@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>

//全局tableView

@property (nonatomic,strong)UITableView *tableView;

//全局滚动按钮

@property (nonatomic,strong)UIButton *btnTop;

@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    //添加tableView

    [self.viewaddSubview:self.tableView];

     //添加滚动按钮

    [selfscrollTopView];


}

#pragma mark - 设置tableView

- (UITableView *)tableView

{

    if (!_tableView) {

        _tableView = [[UITableViewalloc]init];

        _tableView.frame =CGRectMake(0,64,self.view.frame.size.width , self.view.frame.size.height);

        _tableView.backgroundColor = [UIColorlightGrayColor];

        _tableView.delegate =self;

        _tableView.dataSource =self;

        _tableView.separatorStyle =UITableViewCellSeparatorStyleSingleLine;

        

    }

    return_tableView;

}

#pragma mark - tableView 数据源-


//共多少组

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    

    return1;

}

//每组有多少行

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return100;

    

}

//每行显示的内容

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    

    //创建标识符

    staticNSString *cellId =@"cellid";

    UITableViewCell *cell = [tableViewdequeueReusableCellWithIdentifier:cellId];

    

    //缓存池

    if (!cell) {

        cell = [[UITableViewCellalloc]initWithStyle:UITableViewCellStyleSubtitlereuseIdentifier:cellId];

    }

    //标题

    cell.textLabel.text = [NSStringstringWithFormat:@" %ld",(long)indexPath.row];

    return cell;

}

//创建滚动顶部按钮

- (void)scrollTopView

{

    _btnTop= [[UIButtonalloc]init];

    _btnTop.frame =CGRectMake(self.view.bounds.size.width -54,self.view.bounds.size.height -98, 44, 44);

    

    //添加图片

    [_btnTopsetImage:[UIImageimageNamed:@"icon_up"]forState:UIControlStateNormal];

    //设置先隐藏

    _btnTop.hidden =YES;

    //设置背景颜色方便测试

    [_btnTopsetBackgroundColor:[UIColororangeColor]];

    //监听

    [_btnTopaddTarget:selfaction:@selector(btnClick)forControlEvents:UIControlEventTouchUpInside];

    //添加视图

    [self.viewaddSubview:_btnTop];

}

#pragma mark

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{

    //动态计算高度

    CGFloat gap =self.tableView.contentOffset.y -  scrollView.frame.size.height *1.5;

    if (gap <0) {

        //设置小于0隐藏

        self.btnTop.hidden =YES;

        

    } else {

        //设置大于0显示

        self.btnTop.hidden =NO;

    }

}


- (void)btnClick

{

 //回到顶部

 [self.tableViewsetContentOffset:CGPointZero];

}


@end




原创粉丝点击