UIScrollView 底层实现方式

引言:

在 iOS 开发中我们会大量用到 scrollView 这个控件,我们使用的 tableView/collectionview/textView 都继承自它。scrollView 的频繁使用让我对它的底层实现产生了兴趣,它到底是如何工作的?如何实现一个 scrollView ?

我们首先来思考以下几个问题:

  • scrollView 继承自谁,它如何检测到手指滑动?
  • scrollView 如何实现滚动?
  • scrollView 里的各种属性是如何实现的?如contentSize/contentOffSet……

通过一步步解决上边的问题,我们就能实现一个自己的 scrollView。


# 一. 添加手势

毫无疑问我们都知道 scrollView 继承自 UIView,检测手指滑动应该是在 view 上放置了一个手势识别,实现代码如下:


- (instancetype)initWithFrame:(CGRect)frame {
	self = [super initWithFrame:frame];
	if (self) {
		UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] init];
		[panGesture addTarget:self action:@selector(panGestureAction:)];
		[self addGestureRecognizer:panGesture];
	}
	return self;
}

# 二. frame 和 bounds

要搞清楚第二个问题,首先我们必须理解 frame 和 bounds 的概念:

提到它们,大家都知道frame是相对于父视图坐标系来说自己的位置和尺寸,bounds 相对于自身坐标系来说的位置和尺寸,并且 origin 一般为(0,0)。但是boundsorigin 有什么用处?改变它会出现什么效果呢?

当我们尝试改变boundsorigin 时,我们就会发现视图本身没有发生变化,但是它的子视图的位置却发生了变化,why???其实当我们改变boundsorigin 的时候,视图本身位置没有变化,但是由于 origin 的值是基于自身的坐标系,所以自身坐标系的位置被我们改变了。而子视图的 frame 正是基于父视图的坐标系,当我们更改父视图 bounds 中 origin 的时候子视图的位置就发生了变化,这就是实现 scrollView 的关键点!!!

是不是很好理解? 基于这点我们很容易实现一个简单的最初级版本的scrollView,代码如下:


- (void)panGestureAction:(UIPanGestureRecognizer *)pan {
	// 记录每次滑动开始时的初始位置
	if (pan.state == UIGestureRecognizerStateBegan) {
		self.startLocation = self.bounds.origin;
		NSLog(@"%@", NSStringFromCGPoint(self.startLocation));
	}

	// 相对于初始触摸点的偏移量
	if (pan.state == UIGestureRecognizerStateChanged) {
		CGPoint point = [pan translationInView:self];
		NSLog(@"%@", NSStringFromCGPoint(point));
		CGFloat newOriginalX = self.startLocation.x - point.x;
		CGFloat newOriginalY = self.startLocation.y - point.y;
		CGRect bounds = self.bounds;
		bounds.origin = CGPointMake(newOriginalX, newOriginalY);
		self.bounds = bounds;
	}
}

# 三. 优化

理解了上边内容的关键点,下边我们将对我们实现的 scrollView 做一个简单的优化:

通过 contentSize 限制 scrollView 的内部空间,实现代码如下:


CGFloat maxMoveWidth = 1000;
CGFloat maxMoveHeight = 1000;
if (newOriginalX > maxMoveWidth) {
	newOriginalX = maxMoveWidth;
}
if (newOriginalY > maxMoveHeight) {
	newOriginalY = maxMoveHeight;
}

通过 contentOffset 设置 scrollView 的初始偏移量,相信大家已经懂了如何设置偏移量了吧?没错我们只需设置 view 自身 bounds 的 origin 是实现代码如下:

- (void)setContentOffset:(CGPoint)contentOffset {
	_contentOffset = contentOffset;
	CGRect newBounds = self.bounds;
	newBounds.origin = contentOffset;
	self.bounds = newBounds;
}

防止 scrollView 的子视图超出 scrollView:

self.layer.masksToBounds = YES;