一、场景
在我们的app中需要一个类似影院传送带式选择电影场次的控件,效果如下:
二、实现思路
- 控件选择
看控件特征,是一个可滚动的长列表,在iOS中一般都使用UICollectionView
来展现,这里我们也选择它。 - 布局选择
UICollectionView
中每个item
的显示样式都通过UICollectionViewLayout
来控制,这里明显是一个“流式布局”,我们可以选择UICollectionViewFlowLayout
来定制样式。 - 布局控制
在上面的显示效果中,我们需要控制两个点:- 缩放效果
// 该方法指定UICollectionView的每个item滚动到相应rect的显示效果(UICollectionViewLayoutAttributes,包含尺寸、透明度等信息) open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]?
- 滚动结束,定位到中间位置
// 该方法指定UICollectionView滚动到的目标位置 // a layout can return the content offset to be applied during transition or update animations open func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint
- 缩放效果
三、实现细节
- 缩放效果
override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let superAttributes = super.layoutAttrib