关于UIScollView中的contentOffset的理解


大家对UIScollView 中的contentOffset 一直有疑问。 当时我也有好多疑问,后来在网上找了一下资料,发现没有找到合理的解释,因此自己就查看了一下官方文档,自己好好的研究了一番。

现就自己总结的结论截屏分享给大家, 有争议的地方可以一块讨论。

官方解释:

contentOffset : A CGPoint value that defines the top-left corner of the scroll view bounds.

偏移量:scroll view的左上角(在本地坐标系中)的坐标点,其实就是scroll view的bounds的origin点。

我们可以通过打印来验证,仔细看下图。

 1 #import "ViewController.h"
 2 
 3 @interface ViewController ()<UIScrollViewDelegate>
 4 
 5 @property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
 6 @end
 7 
 8 @implementation ViewController
 9 
10 - (void)viewDidLoad {
11     [super viewDidLoad];
12     self.scrollView.contentSize = CGSizeMake(400, 400);
13     UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
14     redView.backgroundColor = [UIColor redColor];
15     [self.scrollView addSubview:redView];
16     self.scrollView.delegate = self;
17    
18 }
19 - (void)scrollViewDidScroll:(UIScrollView *)scrollView{
20     
21     
22     NSLog(@"self.scrollView.contentOffset.x = %f, self.scrollView.contentOffset.y = %f",self.scrollView.contentOffset.x,self.scrollView.contentOffset.y);
23     
24     NSLog(@"self.scrollView.bounds.origin.x = %f, self.scrollView.bounds.origin.y = %f",self.scrollView.bounds.origin.x,self.scrollView.bounds.origin.y);
25     
26     NSLog(@"********************************************************************************************");
27 }
28 
29 
30 @end
View Code

为什么在UIScollView 中的向右下拖动内容,contentOffset的x和y值会变小,甚至成为负值呢?

我们在拖动content的时候,坐标系原点也会跟随conten一起移动,附上图方便理解。

 

原文地址:https://www.cnblogs.com/chao8888/p/5332579.html