iOS UI布局-回到顶部
2015-11-09 10:22 jiangys 阅读(1411) 评论(0) 编辑 收藏 举报回到顶部,是比较常用的一个效果
核心代码
在ViewDidLoad中,添加回到顶部按钮
计算偏移量,如果当前显示的内容全部向上隐藏掉,则显示“回到顶部”按钮
// // ViewController.m // 回到顶部 // // Created by Apple on 15/11/4. // Copyright © 2015年 Apple. All rights reserved. // #import "ViewController.h" @interface ViewController () <UITableViewDelegate,UITableViewDataSource> @property(nonatomic, strong)UITableView *tableView; @property (nonatomic, strong) UIButton * topBtn; @property (nonatomic, assign) CGFloat lastContentOffset; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]; self.tableView.delegate = self; self.tableView.dataSource = self; [self.view addSubview:_tableView]; // 添加回到顶部按钮 _topBtn = [UIButton buttonWithType:UIButtonTypeCustom]; _topBtn.frame = CGRectMake(self.view.frame.size.width-60, self.view.frame.size.height-100, 40, 40); [_topBtn setBackgroundImage:[UIImage imageNamed:@"nearby_return_top_btn"] forState:UIControlStateNormal]; [_topBtn addTarget:self action:@selector(backToTopButton) forControlEvents:UIControlEventTouchUpInside]; _topBtn.clipsToBounds = YES; _topBtn.hidden = YES; [self.view addSubview:_topBtn]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 60; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CMainCell = @"CMainCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CMainCell]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CMainCell]; } cell.textLabel.text =[NSString stringWithFormat:@"测试广本%u",indexPath.row]; return cell; } // MARK: 计算偏移量 - (void)scrollViewDidScroll:(UIScrollView *)scrollView { //MARK:列表滑动偏移量计算 CGPoint point = [self.tableView contentOffset]; if (point.y >= self.tableView.frame.size.height) { self.topBtn.hidden = NO; [self.view bringSubviewToFront:self.topBtn]; } else { self.topBtn.hidden = YES; } } //MARK: 点击移动到顶部 - (void)backToTopButton{ [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
效果:
源代码下载链接:http://pan.baidu.com/s/1c0c7t3E