LoginSignup
1
0

More than 5 years have passed since last update.

【PageMenu】コードからタブインデックスを元にページをスクロールさせる【Swift3.0】

Last updated at Posted at 2016-12-19

便利なPageMenuですが、タブのインデックスを元にページをスクロールさせるメソッドがないようなので(2016.12.18時点)、自分でCAPSPageMenu.swiftに追加して使ってます。

scrollViewByTabIndex

    // swift 3.0

    // MARK: - Scroll view by Tab index

    func scrollViewByTabIndex(_ itemIndex:Int) {
        if itemIndex >= 0 && itemIndex < controllerArray.count {
            // Update page if changed
            if itemIndex != currentPageIndex {
                startingPageForScroll = itemIndex
                lastPageIndex = currentPageIndex
                currentPageIndex = itemIndex
                didTapMenuItemToScroll = true

                // Add pages in between current and tapped page if necessary
                let smallerIndex : Int = lastPageIndex < currentPageIndex ? lastPageIndex : currentPageIndex
                let largerIndex : Int = lastPageIndex > currentPageIndex ? lastPageIndex : currentPageIndex

                if smallerIndex + 1 != largerIndex {
                    for index in (smallerIndex + 1)...(largerIndex - 1) {
                        if pagesAddedDictionary[index] != index {
                            addPageAtIndex(index)
                            pagesAddedDictionary[index] = index
                        }
                    }
                }

                addPageAtIndex(itemIndex)

                // Add page from which tap is initiated so it can be removed after tap is done
                pagesAddedDictionary[lastPageIndex] = lastPageIndex
            }

            // Move controller scroll view when tapping menu item
            let duration : Double = Double(scrollAnimationDurationOnMenuItemTap) / Double(1000)

            UIView.animate(withDuration: duration, animations: { () -> Void in
                let xOffset : CGFloat = CGFloat(itemIndex) * self.controllerScrollView.frame.width
                self.controllerScrollView.setContentOffset(CGPoint(x: xOffset, y: self.controllerScrollView.contentOffset.y), animated: false)
            })

            if tapTimer != nil {
                tapTimer!.invalidate()
            }

            let timerInterval : TimeInterval = Double(scrollAnimationDurationOnMenuItemTap) * 0.001
            tapTimer = Timer.scheduledTimer(timeInterval: timerInterval, target: self, selector: #selector(CAPSPageMenu.scrollViewDidEndTapScrollingAnimation), userInfo: nil, repeats: false)
        }

    }

呼び出し

たとえば左から2番目のページをスクロールさせるにはこのようにします。

pageMenu?.scrollViewByTabIndex(1) 

ちなみにuacaps/PageMenuさんへはプルリク済みです。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0