以下图为例,图片,红色view和蓝色view是添加在scrollView上的,向上拖动,红色view停留在屏幕顶端不动,其它的继续滚动,向下拖动后,红色view跟着下来
代码如下:(注意的是scrollView中自动布局的设置问题)
1 #import "ViewController.h"
2 @interface ViewController () <UIScrollViewDelegate>
3 @property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
4 @property (weak, nonatomic) IBOutlet UIView *blueView;
5 @property (weak, nonatomic) IBOutlet UIView *redView;
6 @property (weak, nonatomic) IBOutlet UIImageView *imageView;
7 @end
8 @implementation ViewController
9 - (void)viewDidLoad {
10 [super viewDidLoad];
11 self.scrollView.contentSize = CGSizeMake(0, CGRectGetMaxY(self.blueView.frame));
12 }
13
14 - (void)scrollViewDidScroll:(UIScrollView *)scrollView
15 {
16 CGFloat imageH = self.imageView.frame.size.height;
17 CGFloat offsetY = scrollView.contentOffset.y;
18 if (offsetY >= imageH) {
19 //将红色控件添加到控制器View中
20 CGRect redFrame = self.redView.frame;
21 redFrame.origin.y = 0;
22 self.redView.frame = redFrame;
23 [self.view addSubview:self.redView];
24 }else {
25 //将红色控件添加到控制器scrollView中
26 CGRect redFrame = self.redView.frame;
27 redFrame.origin.y = 140;
28 self.redView.frame = redFrame;
29 [self.scrollView addSubview:self.redView];
30 }
31
32 // if (offsetY < 0) {
33 // CGFloat scale = 1 - (offsetY / 80);
34 // self.imageView.transform = CGAffineTransformMakeScale(scale, scale);
35 // }
36
37 CGFloat scale = 1 - (offsetY / 20);
38 scale = (scale >= 1) ? scale : 1;
39 self.imageView.transform = CGAffineTransformMakeScale(scale, scale);
40 }
41 @end