iOS 滚动到顶部

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

注意:整份代码直接拷贝过去就可以实现下面效果

效果图:

#import "ViewController.h"

@interface ViewController ()

//全局tableView

@property (nonatomic,strong)UITableView *tableView;

//全局滚动按钮

@property (nonatomic,strong)UIButton *btnTop;

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

//添加tableView

[self.view addSubview:self.tableView];

//添加滚动按钮

[self scrollTopView];

}

#pragma mark - 设置tableView

- (UITableView *)tableView

{

if (!_tableView) {

_tableView = [[UITableView alloc]init];

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

_tableView.backgroundColor = [UIColor lightGrayColor];

_tableView.delegate = self;

_tableView.dataSource = self;

_tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;

}

return _tableView;

}

#pragma mark - tableView 数据源-

//共多少组

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

return 1;

}

//每组有多少行

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

return 100;

}

//每行显示的内容

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

//创建标识符

static NSString *cellId = @"cellid";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];

//缓存池

if (!cell) {

cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];

}

//标题

cell.textLabel.text = [NSString stringWithFormat:@"第 %ld 个",(long)indexPath.row];

return cell;

}

//创建滚动顶部按钮

- (void)scrollTopView

{

_btnTop= [[UIButton alloc]init];

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

//添加图片

[_btnTop setImage:[UIImage imageNamed:@"icon_up"] forState:UIControlStateNormal];

//设置先隐藏

_btnTop.hidden = YES;

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

[_btnTop setBackgroundColor:[UIColor orangeColor]];

//监听

[_btnTop addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];

//添加视图

[self.view addSubview:_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.tableView setContentOffset:CGPointZero];

}

@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容