关于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
为什么在UIScollView 中的向右下拖动内容,contentOffset的x和y值会变小,甚至成为负值呢?
我们在拖动content的时候,坐标系原点也会跟随conten一起移动,附上图方便理解。
Super
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)