前言:发现在很多的app中都会采用到这个scrollview悬停(想了解的看一看)
#import "ViewController.h"
@interface ViewController ()<UIScrollViewDelegate>
@property (nonatomic, strong) UIScrollView *scView;
@property (nonatomic, strong) UIView *topView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIScrollView *scView = [[UIScrollView alloc]initWithFrame:[UIScreen mainScreen].bounds];
[self.view addSubview:scView];
scView.backgroundColor = [UIColor redColor];
scView.contentSize = CGSizeMake(self.view.frame.size.width, 1000);
//创建一个button
UIButton *but = [[UIButton alloc]initWithFrame:CGRectMake(100, 400, 100, 100)];
[scView addSubview:but];
but.backgroundColor = [UIColor greenColor];
//创建顶部的条
UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, 50)];
topView.backgroundColor = [UIColor greenColor];
[scView addSubview:topView];
self.topView = topView;
self.scView = scView;
self.scView.delegate = self;
}
#pragma scrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
if (self.scView.contentOffset.y > 100) {
self.topView.frame = CGRectMake(0, 0, self.view.frame.size.width, 50) ;
[self.view addSubview:self.topView];
}else{
self.topView.frame = CGRectMake(0, 100, self.view.frame.size.width, 50) ;
[self.scView addSubview:self.topView];
}
}
@end
基本思路就是代理监听scrollview滑动时的偏移量,如果偏移量大于悬浮控件到屏幕顶端的距离,那么就将悬浮控件添加到根控制的view,如果偏移量小于这个距离时,再把悬浮控件添加到最表面的scrollView,注意:悬浮控件每次更改父控件时候都需要更改自己的坐标。