iOS UI布局-回到顶部

iOS UI布局-回到顶部,第1张

iOS UI布局-回到顶部

回到顶部,是比较常用的一个效果

核心代码

在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(, , 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-, self.view.frame.size.height-, , );
[_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 ;
} -(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(, ) animated:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} @end

效果:

源代码下载链接:http://pan.baidu.com/s/1c0c7t3E

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/586049.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-12
下一篇 2022-04-12

发表评论

登录后才能评论

评论列表(0条)

保存