8.编写Home页面 -PageTitleView 和PageC
编写两个自定义控件之间的关联关系
1.监听PageTitleView中的点击
1.1将PageTitleView中点击逻辑进行处理
1.2告知PageContentView滚动到正确的控制器
// MARK:-监听Label的点击
extensionPageTitleView{
@objcfileprivatefunctitleLabelClick(_tapGes :UITapGestureRecognizer) {
// 0.获取当前Label
guardletcurrentLabel = tapGes.viewas?UILabelelse{return}
// 1.如果是重复点击同一个Title,那么直接返回
ifcurrentLabel.tag==currentIndex{return}
// 2.获取之前的Label
letoldLabel =titleLabels[currentIndex]
// 3.切换文字的颜色
currentLabel.textColor=UIColor(r:kSelectColor.0, g:kSelectColor.1, b:kSelectColor.2)
oldLabel.textColor=UIColor(r:kNormalColor.0, g:kNormalColor.1, b:kNormalColor.2)
// 4.保存最新Label的下标值
currentIndex= currentLabel.tag
// 5.滚动条位置发生改变
let scrollLineX =CGFloat(currentIndex) *scrollLine.frame.width
UIView.animate(withDuration:0.15, animations: {
self.scrollLine.frame.origin.x= scrollLineX
})
// 6.通知代理
delegate?.pageTitleView(self, selectedIndex:currentIndex)
}
}


// 0.获取当前Label
guardletcurrentLabel = tagGes.viewas?UILabelelse{return}
// 1.如果是重复点击同一个Title,那么直接返回
ifcurrentLabel.tag==currentIndex{return}
// 2.获取之前的Label
letoldLabel =titleLabels[currentIndex]
// 3.切换文字的颜色
currentLabel.textColor=UIColor(r:kSelectColor.0, g:kSelectColor.1, b:kSelectColor.2)
oldLabel.textColor=UIColor(r:kNormalColor.0, g:kNormalColor.1, b:kNormalColor.2)
// 4.保存最新Label的下标值
currentIndex= currentLabel.tag
// 5.滚动条位置发生改变
letscrollLineX =CGFloat(currentIndex) *scrollLine.frame.width
UIView.animate(withDuration:0.15, animations: {
self.scrollLine.frame.origin.x= scrollLineX
})

运行效果:点击不同的title ,下标会切换到不同的下标并改变颜色

为了PageTitleView能与下面的PageContentView进行联系,这里先把点击的到label的下标传递给HomeViewController,再由HomeViewController传递给PageContentView
通过代理进行实现这样的通信
// MARK:定义代理,只能被类遵守
protocolPageTitleViewDelegate:class{
funcpageTitleView(_titleView :PageTitleView, selectedIndex index :Int)
}

在类中进行定义代理

到HomeViewController 来成为PagetitleView的代理


点击不同的title 来显示点击到的index


extensionHomeViewController:PageTitleViewDelegate{
func pageTitleView(_titleView:PageTitleView, selectedIndex index:Int) {
pageContentView.setCurrentIndex(index)
}
}

来到PageContentView

fileprivate var isForbidScrollDelegate :Bool = false

运行效果:点击PageTitleView中的title,下面的PageContentViw 滑动到对应的选项

处理PageContentView滚动

遵循collection Delegate协议

//遵循collectionView的Delegate协议
extensionPageContentView:UICollectionViewDelegate{
funcscrollViewWillBeginDragging(_scrollView:UIScrollView) {
print("--")
}
}
测试监听滚动的事件 ,运行,滑动PageContentView 就会打印 --

定义:fileprivatevarisForbidScrollDelegate :Bool=false


