BaseButtonBarPagerTabStripViewController.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. /*****************************************************************************
  2. * BaseButtonBarPageTabStripViewController.swift
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2018 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Carola Nitz <caro # videolan.org>
  9. *
  10. * Refer to the COPYING file of the official project for license.
  11. *****************************************************************************/
  12. import Foundation
  13. class LabelCell: UICollectionViewCell {
  14. @IBOutlet weak var iconLabel: UILabel!
  15. }
  16. public enum SwipeDirection {
  17. case left
  18. case right
  19. case none
  20. }
  21. public struct IndicatorInfo {
  22. public var title: String?
  23. public var accessibilityLabel: String?
  24. public init(title: String) {
  25. self.title = title
  26. self.accessibilityLabel = title
  27. }
  28. }
  29. public enum PagerScroll {
  30. case no
  31. case yes
  32. case scrollOnlyIfOutOfScreen
  33. }
  34. open class BaseButtonBarPagerTabStripViewController<ButtonBarCellType: UICollectionViewCell>: PagerTabStripViewController, PagerTabStripDataSource, PagerTabStripIsProgressiveDelegate, UICollectionViewDelegate, UICollectionViewDataSource {
  35. public var changeCurrentIndexProgressive: ((_ oldCell: ButtonBarCellType?, _ newCell: ButtonBarCellType?, _ progressPercentage: CGFloat, _ changeCurrentIndex: Bool, _ animated: Bool) -> Void)?
  36. @IBOutlet public weak var buttonBarView: ButtonBarView!
  37. lazy private var cachedCellWidths: [CGFloat]? = { [unowned self] in
  38. return self.calculateWidths()
  39. }()
  40. public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
  41. super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
  42. delegate = self
  43. datasource = self
  44. }
  45. @available(*, unavailable, message: "use init(nibName:)")
  46. required public init?(coder aDecoder: NSCoder) {
  47. fatalError()
  48. }
  49. open override func viewDidLoad() {
  50. super.viewDidLoad()
  51. let buttonBarViewAux = buttonBarView ?? {
  52. let flowLayout = UICollectionViewFlowLayout()
  53. flowLayout.scrollDirection = .horizontal
  54. let buttonBar = ButtonBarView(frame: .zero, collectionViewLayout: flowLayout)
  55. buttonBar.backgroundColor = .white
  56. buttonBar.selectedBar.backgroundColor = PresentationTheme.current.colors.orangeUI
  57. buttonBar.scrollsToTop = false
  58. buttonBar.showsHorizontalScrollIndicator = false
  59. buttonBar.selectedBarHeight = 4.0
  60. return buttonBar
  61. }()
  62. buttonBarView = buttonBarViewAux
  63. if buttonBarView.superview == nil {
  64. buttonBarView.translatesAutoresizingMaskIntoConstraints = false
  65. view.addSubview(buttonBarView)
  66. NSLayoutConstraint.activate([
  67. buttonBarView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor),
  68. buttonBarView.rightAnchor.constraint(equalTo: view.rightAnchor),
  69. buttonBarView.leftAnchor.constraint(equalTo: view.leftAnchor),
  70. buttonBarView.heightAnchor.constraint(equalToConstant: 35)
  71. ])
  72. NSLayoutConstraint.activate([
  73. containerView.topAnchor.constraint(equalTo: buttonBarView.bottomAnchor),
  74. containerView.rightAnchor.constraint(equalTo: view.rightAnchor),
  75. containerView.leftAnchor.constraint(equalTo: view.leftAnchor),
  76. containerView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
  77. ]
  78. )
  79. }
  80. buttonBarView.delegate = self
  81. buttonBarView.dataSource = self
  82. // register button bar item cell
  83. buttonBarView.register(UINib(nibName: "LabelCell", bundle: .main), forCellWithReuseIdentifier:"Cell")
  84. }
  85. open override func viewWillAppear(_ animated: Bool) {
  86. super.viewWillAppear(animated)
  87. buttonBarView.layoutIfNeeded()
  88. isViewAppearing = true
  89. }
  90. open override func viewDidAppear(_ animated: Bool) {
  91. super.viewDidAppear(animated)
  92. isViewAppearing = false
  93. }
  94. open override func viewDidLayoutSubviews() {
  95. super.viewDidLayoutSubviews()
  96. guard isViewAppearing || isViewRotating else { return }
  97. // Force the UICollectionViewFlowLayout to get laid out again with the new size if
  98. // a) The view is appearing. This ensures that
  99. // collectionView:layout:sizeForItemAtIndexPath: is called for a second time
  100. // when the view is shown and when the view *frame(s)* are actually set
  101. // (we need the view frame's to have been set to work out the size's and on the
  102. // first call to collectionView:layout:sizeForItemAtIndexPath: the view frame(s)
  103. // aren't set correctly)
  104. // b) The view is rotating. This ensures that
  105. // collectionView:layout:sizeForItemAtIndexPath: is called again and can use the views
  106. // *new* frame so that the buttonBarView cell's actually get resized correctly
  107. cachedCellWidths = calculateWidths()
  108. buttonBarView.collectionViewLayout.invalidateLayout()
  109. // When the view first appears or is rotated we also need to ensure that the barButtonView's
  110. // selectedBar is resized and its contentOffset/scroll is set correctly (the selected
  111. // tab/cell may end up either skewed or off screen after a rotation otherwise)
  112. buttonBarView.moveTo(index: currentIndex, animated: false, swipeDirection: .none, pagerScroll: .scrollOnlyIfOutOfScreen)
  113. buttonBarView.selectItem(at: IndexPath(item: currentIndex, section: 0), animated: false, scrollPosition: [])
  114. }
  115. // MARK: - Public Methods
  116. open override func reloadPagerTabStripView() {
  117. super.reloadPagerTabStripView()
  118. guard isViewLoaded else { return }
  119. buttonBarView.reloadData()
  120. cachedCellWidths = calculateWidths()
  121. buttonBarView.moveTo(index: currentIndex, animated: false, swipeDirection: .none, pagerScroll: .yes)
  122. }
  123. open func calculateStretchedCellWidths(_ minimumCellWidths: [CGFloat], suggestedStretchedCellWidth: CGFloat, previousNumberOfLargeCells: Int) -> CGFloat {
  124. var numberOfLargeCells = 0
  125. var totalWidthOfLargeCells: CGFloat = 0
  126. for minimumCellWidthValue in minimumCellWidths where minimumCellWidthValue > suggestedStretchedCellWidth {
  127. totalWidthOfLargeCells += minimumCellWidthValue
  128. numberOfLargeCells += 1
  129. }
  130. guard numberOfLargeCells > previousNumberOfLargeCells else { return suggestedStretchedCellWidth }
  131. let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout // swiftlint:disable:this force_cast
  132. let collectionViewAvailiableWidth = buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right
  133. let numberOfCells = minimumCellWidths.count
  134. let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing
  135. let numberOfSmallCells = numberOfCells - numberOfLargeCells
  136. let newSuggestedStretchedCellWidth = (collectionViewAvailiableWidth - totalWidthOfLargeCells - cellSpacingTotal) / CGFloat(numberOfSmallCells)
  137. return calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: newSuggestedStretchedCellWidth, previousNumberOfLargeCells: numberOfLargeCells)
  138. }
  139. open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int) {
  140. guard shouldUpdateButtonBarView else { return }
  141. buttonBarView.moveTo(index: toIndex, animated: true, swipeDirection: toIndex < fromIndex ? .right : .left, pagerScroll: .yes)
  142. }
  143. open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool) {
  144. guard shouldUpdateButtonBarView else { return }
  145. buttonBarView.move(fromIndex: fromIndex, toIndex: toIndex, progressPercentage: progressPercentage, pagerScroll: .yes)
  146. if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
  147. let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex != fromIndex ? fromIndex : toIndex, section: 0)) as? ButtonBarCellType
  148. let newCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarCellType
  149. changeCurrentIndexProgressive(oldCell, newCell, progressPercentage, indexWasChanged, true)
  150. }
  151. }
  152. // MARK: - UICollectionViewDelegateFlowLayut
  153. @objc open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
  154. guard let cellWidthValue = cachedCellWidths?[indexPath.row] else {
  155. fatalError("cachedCellWidths for \(indexPath.row) must not be nil")
  156. }
  157. return CGSize(width: cellWidthValue, height: collectionView.frame.size.height)
  158. }
  159. open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  160. guard indexPath.item != currentIndex else { return }
  161. buttonBarView.moveTo(index: indexPath.item, animated: true, swipeDirection: .none, pagerScroll: .yes)
  162. shouldUpdateButtonBarView = false
  163. let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarCellType
  164. let newCell = buttonBarView.cellForItem(at: IndexPath(item: indexPath.item, section: 0)) as? ButtonBarCellType
  165. if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
  166. changeCurrentIndexProgressive(oldCell, newCell, 1, true, true)
  167. }
  168. moveToViewController(at: indexPath.item)
  169. }
  170. // MARK: - UICollectionViewDataSource
  171. open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  172. return viewControllers.count
  173. }
  174. open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  175. guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? ButtonBarCellType else {
  176. fatalError("UICollectionViewCell should be or extend from ButtonBarViewCell")
  177. }
  178. let childController = viewControllers[indexPath.item] as! IndicatorInfoProvider // swiftlint:disable:this force_cast
  179. let indicatorInfo = childController.indicatorInfo(for: self)
  180. configure(cell: cell, for: indicatorInfo)
  181. if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
  182. changeCurrentIndexProgressive(currentIndex == indexPath.item ? nil : cell, currentIndex == indexPath.item ? cell : nil, 1, true, false)
  183. }
  184. return cell
  185. }
  186. // MARK: - UIScrollViewDelegate
  187. open override func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
  188. super.scrollViewDidEndScrollingAnimation(scrollView)
  189. guard scrollView == containerView else { return }
  190. shouldUpdateButtonBarView = true
  191. }
  192. open func configure(cell: ButtonBarCellType, for indicatorInfo: IndicatorInfo) {
  193. fatalError("You must override this method to set up ButtonBarView cell accordingly")
  194. }
  195. private func calculateWidths() -> [CGFloat] {
  196. let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout // swiftlint:disable:this force_cast
  197. let numberOfCells = viewControllers.count
  198. var minimumCellWidths = [CGFloat]()
  199. var collectionViewContentWidth: CGFloat = 0
  200. let indicatorWidth:CGFloat = 70.0
  201. viewControllers.forEach { _ in
  202. minimumCellWidths.append(indicatorWidth)
  203. collectionViewContentWidth += indicatorWidth
  204. }
  205. let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing
  206. collectionViewContentWidth += cellSpacingTotal
  207. let collectionViewAvailableVisibleWidth = buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right
  208. if collectionViewAvailableVisibleWidth < collectionViewContentWidth {
  209. return minimumCellWidths
  210. } else {
  211. let stretchedCellWidthIfAllEqual = (collectionViewAvailableVisibleWidth - cellSpacingTotal) / CGFloat(numberOfCells)
  212. let generalMinimumCellWidth = calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: stretchedCellWidthIfAllEqual, previousNumberOfLargeCells: 0)
  213. var stretchedCellWidths = [CGFloat]()
  214. for minimumCellWidthValue in minimumCellWidths {
  215. let cellWidth = (minimumCellWidthValue > generalMinimumCellWidth) ? minimumCellWidthValue : generalMinimumCellWidth
  216. stretchedCellWidths.append(cellWidth)
  217. }
  218. return stretchedCellWidths
  219. }
  220. }
  221. private var shouldUpdateButtonBarView = true
  222. }
  223. // MARK: Protocols
  224. public protocol IndicatorInfoProvider {
  225. func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo
  226. }
  227. public protocol PagerTabStripIsProgressiveDelegate: class {
  228. func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool)
  229. }
  230. public protocol PagerTabStripDataSource: class {
  231. func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController]
  232. }
  233. // MARK: PagerTabStripViewController
  234. open class PagerTabStripViewController: UIViewController, UIScrollViewDelegate {
  235. @IBOutlet weak public var containerView: UIScrollView!
  236. open weak var delegate: PagerTabStripIsProgressiveDelegate?
  237. open weak var datasource: PagerTabStripDataSource?
  238. open private(set) var viewControllers = [UIViewController]()
  239. open private(set) var currentIndex = 0
  240. open private(set) var preCurrentIndex = 0 // used *only* to store the index to which move when the pager becomes visible
  241. open var pageWidth: CGFloat {
  242. return containerView.bounds.width
  243. }
  244. open var scrollPercentage: CGFloat {
  245. if swipeDirection != .right {
  246. let module = fmod(containerView.contentOffset.x, pageWidth)
  247. return module == 0.0 ? 1.0 : module / pageWidth
  248. }
  249. return 1 - fmod(containerView.contentOffset.x >= 0 ? containerView.contentOffset.x : pageWidth + containerView.contentOffset.x, pageWidth) / pageWidth
  250. }
  251. open var swipeDirection: SwipeDirection {
  252. if containerView.contentOffset.x > lastContentOffset {
  253. return .left
  254. } else if containerView.contentOffset.x < lastContentOffset {
  255. return .right
  256. }
  257. return .none
  258. }
  259. override open func viewDidLoad() {
  260. super.viewDidLoad()
  261. let containerViewAux = containerView ?? {
  262. return UIScrollView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height))
  263. }()
  264. containerView = containerViewAux
  265. if containerView.superview == nil {
  266. containerView.translatesAutoresizingMaskIntoConstraints = false
  267. view.addSubview(containerView)
  268. }
  269. containerView.bounces = true
  270. containerView.alwaysBounceHorizontal = true
  271. containerView.alwaysBounceVertical = false
  272. containerView.scrollsToTop = false
  273. containerView.delegate = self
  274. containerView.showsVerticalScrollIndicator = false
  275. containerView.showsHorizontalScrollIndicator = false
  276. containerView.isPagingEnabled = true
  277. containerView.backgroundColor = PresentationTheme.current.colors.background
  278. reloadViewControllers()
  279. let childController = viewControllers[currentIndex]
  280. addChildViewController(childController)
  281. childController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
  282. containerView.addSubview(childController.view)
  283. childController.didMove(toParentViewController: self)
  284. }
  285. open override func viewWillAppear(_ animated: Bool) {
  286. super.viewWillAppear(animated)
  287. isViewAppearing = true
  288. childViewControllers.forEach { $0.beginAppearanceTransition(true, animated: animated) }
  289. }
  290. override open func viewDidAppear(_ animated: Bool) {
  291. super.viewDidAppear(animated)
  292. lastSize = containerView.bounds.size
  293. updateIfNeeded()
  294. let needToUpdateCurrentChild = preCurrentIndex != currentIndex
  295. if needToUpdateCurrentChild {
  296. moveToViewController(at: preCurrentIndex)
  297. }
  298. isViewAppearing = false
  299. childViewControllers.forEach { $0.endAppearanceTransition() }
  300. }
  301. open override func viewWillDisappear(_ animated: Bool) {
  302. super.viewWillDisappear(animated)
  303. childViewControllers.forEach { $0.beginAppearanceTransition(false, animated: animated) }
  304. }
  305. open override func viewDidDisappear(_ animated: Bool) {
  306. super.viewDidDisappear(animated)
  307. childViewControllers.forEach { $0.endAppearanceTransition() }
  308. }
  309. override open func viewDidLayoutSubviews() {
  310. super.viewDidLayoutSubviews()
  311. updateIfNeeded()
  312. }
  313. open override var shouldAutomaticallyForwardAppearanceMethods: Bool {
  314. return false
  315. }
  316. open func moveToViewController(at index: Int, animated: Bool = true) {
  317. guard isViewLoaded && view.window != nil && currentIndex != index else {
  318. preCurrentIndex = index
  319. return
  320. }
  321. if animated && abs(currentIndex - index) > 1 {
  322. var tmpViewControllers = viewControllers
  323. let currentChildVC = viewControllers[currentIndex]
  324. let fromIndex = currentIndex < index ? index - 1 : index + 1
  325. let fromChildVC = viewControllers[fromIndex]
  326. tmpViewControllers[currentIndex] = fromChildVC
  327. tmpViewControllers[fromIndex] = currentChildVC
  328. pagerTabStripChildViewControllersForScrolling = tmpViewControllers
  329. containerView.setContentOffset(CGPoint(x: pageOffsetForChild(at: fromIndex), y: 0), animated: false)
  330. (navigationController?.view ?? view).isUserInteractionEnabled = !animated
  331. containerView.setContentOffset(CGPoint(x: pageOffsetForChild(at: index), y: 0), animated: true)
  332. } else {
  333. (navigationController?.view ?? view).isUserInteractionEnabled = !animated
  334. containerView.setContentOffset(CGPoint(x: pageOffsetForChild(at: index), y: 0), animated: animated)
  335. }
  336. }
  337. open func moveTo(viewController: UIViewController, animated: Bool = true) {
  338. moveToViewController(at: viewControllers.index(of: viewController)!, animated: animated)
  339. }
  340. // MARK: - PagerTabStripDataSource
  341. open func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] {
  342. assertionFailure("Sub-class must implement the PagerTabStripDataSource viewControllers(for:) method")
  343. return []
  344. }
  345. // MARK: - Helpers
  346. open func updateIfNeeded() {
  347. if isViewLoaded && !lastSize.equalTo(containerView.bounds.size) {
  348. updateContent()
  349. }
  350. }
  351. open func canMoveTo(index: Int) -> Bool {
  352. return currentIndex != index && viewControllers.count > index
  353. }
  354. open func pageOffsetForChild(at index: Int) -> CGFloat {
  355. return CGFloat(index) * containerView.bounds.width
  356. }
  357. open func offsetForChild(at index: Int) -> CGFloat {
  358. return (CGFloat(index) * containerView.bounds.width) + ((containerView.bounds.width - view.bounds.width) * 0.5)
  359. }
  360. public enum PagerTabStripError: Error {
  361. case viewControllerOutOfBounds
  362. }
  363. open func offsetForChild(viewController: UIViewController) throws -> CGFloat {
  364. guard let index = viewControllers.index(of: viewController) else {
  365. throw PagerTabStripError.viewControllerOutOfBounds
  366. }
  367. return offsetForChild(at: index)
  368. }
  369. open func pageFor(contentOffset: CGFloat) -> Int {
  370. let result = virtualPageFor(contentOffset: contentOffset)
  371. return pageFor(virtualPage: result)
  372. }
  373. open func virtualPageFor(contentOffset: CGFloat) -> Int {
  374. return Int((contentOffset + 1.5 * pageWidth) / pageWidth) - 1
  375. }
  376. open func pageFor(virtualPage: Int) -> Int {
  377. if virtualPage < 0 {
  378. return 0
  379. }
  380. if virtualPage > viewControllers.count - 1 {
  381. return viewControllers.count - 1
  382. }
  383. return virtualPage
  384. }
  385. open func updateContent() {
  386. if lastSize.width != containerView.bounds.size.width {
  387. lastSize = containerView.bounds.size
  388. containerView.contentOffset = CGPoint(x: pageOffsetForChild(at: currentIndex), y: 0)
  389. }
  390. lastSize = containerView.bounds.size
  391. let pagerViewControllers = pagerTabStripChildViewControllersForScrolling ?? viewControllers
  392. containerView.contentSize = CGSize(width: containerView.bounds.width * CGFloat(pagerViewControllers.count), height: containerView.contentSize.height)
  393. for (index, childController) in pagerViewControllers.enumerated() {
  394. let pageOffsetForChild = self.pageOffsetForChild(at: index)
  395. if fabs(containerView.contentOffset.x - pageOffsetForChild) < containerView.bounds.width {
  396. if childController.parent != nil {
  397. childController.view.frame = CGRect(x: offsetForChild(at: index), y: 0, width: view.bounds.width, height: containerView.bounds.height)
  398. childController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
  399. } else {
  400. childController.beginAppearanceTransition(true, animated: false)
  401. addChildViewController(childController)
  402. childController.view.frame = CGRect(x: offsetForChild(at: index), y: 0, width: view.bounds.width, height: containerView.bounds.height)
  403. childController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
  404. containerView.addSubview(childController.view)
  405. childController.didMove(toParentViewController: self)
  406. childController.endAppearanceTransition()
  407. }
  408. } else {
  409. if childController.parent != nil {
  410. childController.beginAppearanceTransition(false, animated: false)
  411. childController.willMove(toParentViewController: nil)
  412. childController.view.removeFromSuperview()
  413. childController.removeFromParentViewController()
  414. childController.endAppearanceTransition()
  415. }
  416. }
  417. }
  418. let oldCurrentIndex = currentIndex
  419. let virtualPage = virtualPageFor(contentOffset: containerView.contentOffset.x)
  420. let newCurrentIndex = pageFor(virtualPage: virtualPage)
  421. currentIndex = newCurrentIndex
  422. preCurrentIndex = currentIndex
  423. let changeCurrentIndex = newCurrentIndex != oldCurrentIndex
  424. if let progressiveDelegate = self as? PagerTabStripIsProgressiveDelegate {
  425. let (fromIndex, toIndex, scrollPercentage) = progressiveIndicatorData(virtualPage)
  426. progressiveDelegate.updateIndicator(for: self, fromIndex: fromIndex, toIndex: toIndex, withProgressPercentage: scrollPercentage, indexWasChanged: changeCurrentIndex)
  427. }
  428. }
  429. open func reloadPagerTabStripView() {
  430. guard isViewLoaded else { return }
  431. for childController in viewControllers where childController.parent != nil {
  432. childController.beginAppearanceTransition(false, animated: false)
  433. childController.willMove(toParentViewController: nil)
  434. childController.view.removeFromSuperview()
  435. childController.removeFromParentViewController()
  436. childController.endAppearanceTransition()
  437. }
  438. reloadViewControllers()
  439. containerView.contentSize = CGSize(width: containerView.bounds.width * CGFloat(viewControllers.count), height: containerView.contentSize.height)
  440. if currentIndex >= viewControllers.count {
  441. currentIndex = viewControllers.count - 1
  442. }
  443. preCurrentIndex = currentIndex
  444. containerView.contentOffset = CGPoint(x: pageOffsetForChild(at: currentIndex), y: 0)
  445. updateContent()
  446. }
  447. // MARK: - UIScrollViewDelegate
  448. open func scrollViewDidScroll(_ scrollView: UIScrollView) {
  449. if containerView == scrollView {
  450. updateContent()
  451. lastContentOffset = scrollView.contentOffset.x
  452. }
  453. }
  454. open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  455. if containerView == scrollView {
  456. lastPageNumber = pageFor(contentOffset: scrollView.contentOffset.x)
  457. }
  458. }
  459. open func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
  460. if containerView == scrollView {
  461. pagerTabStripChildViewControllersForScrolling = nil
  462. (navigationController?.view ?? view).isUserInteractionEnabled = true
  463. updateContent()
  464. }
  465. }
  466. // MARK: - Orientation
  467. open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  468. super.viewWillTransition(to: size, with: coordinator)
  469. isViewRotating = true
  470. pageBeforeRotate = currentIndex
  471. coordinator.animate(alongsideTransition: nil) { [weak self] _ in
  472. guard let me = self else { return }
  473. me.isViewRotating = false
  474. me.currentIndex = me.pageBeforeRotate
  475. me.preCurrentIndex = me.currentIndex
  476. me.updateIfNeeded()
  477. }
  478. }
  479. // MARK: Private
  480. private func progressiveIndicatorData(_ virtualPage: Int) -> (Int, Int, CGFloat) {
  481. let count = viewControllers.count
  482. var fromIndex = currentIndex
  483. var toIndex = currentIndex
  484. let direction = swipeDirection
  485. if direction == .left {
  486. if virtualPage > count - 1 {
  487. fromIndex = count - 1
  488. toIndex = count
  489. } else {
  490. if self.scrollPercentage >= 0.5 {
  491. fromIndex = max(toIndex - 1, 0)
  492. } else {
  493. toIndex = fromIndex + 1
  494. }
  495. }
  496. } else if direction == .right {
  497. if virtualPage < 0 {
  498. fromIndex = 0
  499. toIndex = -1
  500. } else {
  501. if self.scrollPercentage > 0.5 {
  502. fromIndex = min(toIndex + 1, count - 1)
  503. } else {
  504. toIndex = fromIndex - 1
  505. }
  506. }
  507. }
  508. return (fromIndex, toIndex, self.scrollPercentage)
  509. }
  510. private func reloadViewControllers() {
  511. guard let dataSource = datasource else {
  512. fatalError("dataSource must not be nil")
  513. }
  514. viewControllers = dataSource.viewControllers(for: self)
  515. // viewControllers
  516. guard !viewControllers.isEmpty else {
  517. fatalError("viewControllers(for:) should provide at least one child view controller")
  518. }
  519. viewControllers.forEach { if !($0 is IndicatorInfoProvider) { fatalError("Every view controller provided by PagerTabStripDataSource's viewControllers(for:) method must conform to IndicatorInfoProvider") }}
  520. }
  521. private var pagerTabStripChildViewControllersForScrolling: [UIViewController]?
  522. private var lastPageNumber = 0
  523. private var lastContentOffset: CGFloat = 0.0
  524. private var pageBeforeRotate = 0
  525. private var lastSize = CGSize(width: 0, height: 0)
  526. internal var isViewRotating = false
  527. internal var isViewAppearing = false
  528. }