// MARK:- 遵守UICollectionView的数据源
extension PageContentView : UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(kContentCellID, forIndexPath: indexPath)
// 移除之前的
for subview in cell.contentView.subviews {
subview.removeFromSuperview()
}
// 取出控制器
let childVc = childVcs[indexPath.item]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
PageTitleView点击改变PageContentView
通过代理将PageTitleView的事件传递出去
/// 定义协议
protocol PageTitleViewDelegate : class {
func pageTitleView(pageTitleView : PageTitleView, didSelectedIndex index : Int)
}
@objc private func titleLabelClick(tapGes : UITapGestureRecognizer) {
// 1.获取点击的下标志
guard let view = tapGes.view else { return }
let index = view.tag
// 2.滚到正确的位置
scrollToIndex(index)
// 3.通知代理
delegate?.pageTitleView(self, didSelectedIndex: index)
}
内部调整
// 内容滚动
private func scrollToIndex(index : Int) {
// 1.获取最新的label和之前的label
let newLabel = titleLabels[index]
let oldLabel = titleLabels[currentIndex]
// 2.设置label的颜色
newLabel.textColor = kSelectTitleColor
oldLabel.textColor = kNormalTitleColor
// 3.scrollLine滚到正确的位置
let scrollLineEndX = scrollLine.frame.width * CGFloat(index)
UIView.animateWithDuration(0.15) {
self.scrollLine.frame.origin.x = scrollLineEndX
}
// 4.记录index
currentIndex = index
}
在PageContentView中设置当前应该滚动的位置
// MARK:- 对外暴露方法
extension PageContentView {
func scrollToIndex(index : Int) {
let offset = CGPoint(x: CGFloat(index) * collectionViewboundswidth, y: 0)
collectionViewsetContentOffset(offset, animated: false)
}
}
PageContentView滚动调整PageTitleView
通过观察,我们发现:
1> 原来位置的Title颜色会逐渐变暗
2> 目标位置的Title颜色会逐渐变亮
3> 变化程度是和滚动的多少相关
由此得出结论:
我们一共需要获取三个值
1> 起始位置下标值
2> 目标位置下标值
3> 当前滚动的进度
其实前2点可以由第3点计算而来,可以只需要将进度传递出去。
根据进度值处理标题颜色渐变及滑块逻辑










