在完成上述工作后,就可以進(jìn)入流程腥光,首先我們確定初始化定時器后應(yīng)該在什么時候啟動定時器枫弟,很明顯要有接口傳入的數(shù)據(jù)后才開始啟動,所以需要一個有接收并判斷的接口洽腺,這里我們用接收廣告的數(shù)量來實現(xiàn)
//MARK:設(shè)置總頁數(shù)后脚粟,啟動動畫
func setTotalPagesCount(totalPageCout: (()->Int)) {
self.totalPages = totalPageCout()
print("totalPages = \(self.totalPages)")
self.pageControl?.numberOfPages = self.totalPages!
self.currentPageIndex = 0
if self.totalPages == 1 {
scrollView?.contentSize = CGSize(width: MAIN_WIDTH, height: self.bounds.size.height)
configureContentViews()
self.pageControl?.isHidden = true//如果只有一頁不需要顯示pageControl
}else{
self.pageControl?.isHidden = false
}
if self.totalPages! > 0 && self.totalPages! != 1 {
configureContentViews()
self.animationTimer?.resumeTimerAfterInterval(self.animationInterval!)
}
}
定時器啟動
func animationTimerDidFire(timer:Timer){
let index = Int((self.scrollView?.contentOffset.x)!/MAIN_WIDTH)//防止視圖偏移
self.scrollView?.setContentOffset(CGPoint(x: MAIN_WIDTH * CGFloat(index)+MAIN_WIDTH, y: 0),animated: true)
}
獲取數(shù)據(jù)
//獲取數(shù)據(jù)
func setScrollViewDataSource () {
let previousIndex = validateNextPageIndexWithPageIndex(index: self.currentPageIndex! - 1)
let rearIndex = validateNextPageIndexWithPageIndex(index: self.currentPageIndex! + 1)
self.contentViews.removeAll()
if self.contentViewAtIndex != nil {
self.contentViews.append(self.contentViewAtIndex!(previousIndex))//獲取數(shù)據(jù)的接口
self.contentViews.append(self.contentViewAtIndex!(currentPageIndex!))
self.contentViews.append(self.contentViewAtIndex!(rearIndex))
}
}
點擊響應(yīng)
//點擊事件
func contentViewTapped(sender: UIGestureRecognizer){
if self.tapActionBlock != nil {
self.tapActionBlock!(self.currentPageIndex!)
}
}
此外一些常規(guī)的操作依賴于scollView的delegate來完成
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
self.animationTimer?.pauseTimer()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
self.animationTimer?.resumeTimerAfterInterval(self.animationInterval!)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.x >= (MAIN_WIDTH * CGFloat(2)) {
self.currentPageIndex = validateNextPageIndexWithPageIndex(index: self.currentPageIndex!+1)
configureContentViews()
}else if scrollView.contentOffset.x <= 0 {
self.currentPageIndex = validateNextPageIndexWithPageIndex(index: self.currentPageIndex!-1)
configureContentViews()
}
self.pageControl?.currentPage = self.currentPageIndex!
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollView.setContentOffset(CGPoint(x: MAIN_WIDTH, y: 0), animated: true)
}
ok,這就完成了一個banner的簡單封裝,如果有不足謝謝大家指導(dǎo)