BaseButtonBarPagerTabStripViewController.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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 VLCLabelCell: UICollectionViewCell {
  14. static let cellIdentifier = "VLCLabelCell"
  15. @IBOutlet weak var iconLabel: UILabel!
  16. }
  17. enum SwipeDirection {
  18. case left
  19. case right
  20. case none
  21. }
  22. struct IndicatorInfo {
  23. var title: String?
  24. var accessibilityLabel: String?
  25. init(title: String) {
  26. self.title = title
  27. self.accessibilityLabel = title
  28. }
  29. }
  30. enum PagerScroll {
  31. case no
  32. case yes
  33. case onlyIfOutOfScreen
  34. }
  35. class BaseButtonBarPagerTabStripViewController<ButtonBarCellType: UICollectionViewCell>: PagerTabStripViewController, PagerTabStripDataSource, PagerTabStripIsProgressiveDelegate, UICollectionViewDelegate, UICollectionViewDataSource {
  36. var changeCurrentIndexProgressive: ((_ oldCell: ButtonBarCellType?, _ newCell: ButtonBarCellType?, _ progressPercentage: CGFloat, _ changeCurrentIndex: Bool, _ animated: Bool) -> Void)?
  37. var buttonBarView: ButtonBarView!
  38. let buttonbarViewHeight: CGFloat = 45.0
  39. lazy private var cachedCellWidths: [CGFloat]? = { [unowned self] in
  40. return self.calculateWidths()
  41. }()
  42. private var shouldUpdateButtonBarView = true
  43. override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
  44. super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
  45. delegate = self
  46. datasource = self
  47. }
  48. @available(*, unavailable, message: "use init(nibName:)")
  49. required init?(coder aDecoder: NSCoder) {
  50. fatalError()
  51. }
  52. override func viewDidLoad() {
  53. super.viewDidLoad()
  54. let flowLayout = UICollectionViewFlowLayout()
  55. flowLayout.scrollDirection = .horizontal
  56. buttonBarView = ButtonBarView(frame: .zero, collectionViewLayout: flowLayout)
  57. buttonBarView.translatesAutoresizingMaskIntoConstraints = false
  58. view.addSubview(buttonBarView)
  59. NSLayoutConstraint.activate([
  60. buttonBarView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor),
  61. buttonBarView.rightAnchor.constraint(equalTo: view.rightAnchor),
  62. buttonBarView.leftAnchor.constraint(equalTo: view.leftAnchor),
  63. buttonBarView.heightAnchor.constraint(equalToConstant: buttonbarViewHeight)
  64. ])
  65. //make sure that top and bottom are not covered by tabbar and navigationbar
  66. let bottomGuide: NSLayoutConstraint
  67. if #available(iOS 11.0, *) {
  68. bottomGuide = containerView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
  69. } else {
  70. bottomGuide = containerView.bottomAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor)
  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. bottomGuide
  77. ]
  78. )
  79. buttonBarView.delegate = self
  80. buttonBarView.dataSource = self
  81. }
  82. override func viewWillAppear(_ animated: Bool) {
  83. super.viewWillAppear(animated)
  84. buttonBarView.layoutIfNeeded()
  85. isViewAppearing = true
  86. }
  87. override func viewDidAppear(_ animated: Bool) {
  88. super.viewDidAppear(animated)
  89. isViewAppearing = false
  90. }
  91. override func viewDidLayoutSubviews() {
  92. super.viewDidLayoutSubviews()
  93. guard isViewAppearing || isViewRotating else { return }
  94. // Force the UICollectionViewFlowLayout to get laid out again with the new size if
  95. // a) The view is appearing. This ensures that
  96. // collectionView:layout:sizeForItemAtIndexPath: is called for a second time
  97. // when the view is shown and when the view *frame(s)* are actually set
  98. // (we need the view frame's to have been set to work out the size's and on the
  99. // first call to collectionView:layout:sizeForItemAtIndexPath: the view frame(s)
  100. // aren't set correctly)
  101. // b) The view is rotating. This ensures that
  102. // collectionView:layout:sizeForItemAtIndexPath: is called again and can use the views
  103. // *new* frame so that the buttonBarView cell's actually get resized correctly
  104. cachedCellWidths = calculateWidths()
  105. buttonBarView.collectionViewLayout.invalidateLayout()
  106. // When the view first appears or is rotated we also need to ensure that the barButtonView's
  107. // selectedBar is resized and its contentOffset/scroll is set correctly (the selected
  108. // tab/cell may end up either skewed or off screen after a rotation otherwise)
  109. buttonBarView.moveTo(index: currentIndex, animated: false, swipeDirection: .none, pagerScroll: .onlyIfOutOfScreen)
  110. buttonBarView.selectItem(at: IndexPath(item: currentIndex, section: 0), animated: false, scrollPosition: [])
  111. }
  112. // MARK: - Methods
  113. override func reloadPagerTabStripView() {
  114. super.reloadPagerTabStripView()
  115. guard isViewLoaded else { return }
  116. buttonBarView.reloadData()
  117. cachedCellWidths = calculateWidths()
  118. buttonBarView.moveTo(index: currentIndex, animated: false, swipeDirection: .none, pagerScroll: .yes)
  119. }
  120. func calculateStretchedCellWidths(_ minimumCellWidths: [CGFloat], suggestedStretchedCellWidth: CGFloat, previousNumberOfLargeCells: Int) -> CGFloat {
  121. var numberOfLargeCells = 0
  122. var totalWidthOfLargeCells: CGFloat = 0
  123. for minimumCellWidthValue in minimumCellWidths where minimumCellWidthValue > suggestedStretchedCellWidth {
  124. totalWidthOfLargeCells += minimumCellWidthValue
  125. numberOfLargeCells += 1
  126. }
  127. guard numberOfLargeCells > previousNumberOfLargeCells else { return suggestedStretchedCellWidth }
  128. let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout // swiftlint:disable:this force_cast
  129. let collectionViewAvailiableWidth = buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right
  130. let numberOfCells = minimumCellWidths.count
  131. let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing
  132. let numberOfSmallCells = numberOfCells - numberOfLargeCells
  133. let newSuggestedStretchedCellWidth = (collectionViewAvailiableWidth - totalWidthOfLargeCells - cellSpacingTotal) / CGFloat(numberOfSmallCells)
  134. return calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: newSuggestedStretchedCellWidth, previousNumberOfLargeCells: numberOfLargeCells)
  135. }
  136. func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int) {
  137. guard shouldUpdateButtonBarView else { return }
  138. buttonBarView.moveTo(index: toIndex, animated: true, swipeDirection: toIndex < fromIndex ? .right : .left, pagerScroll: .yes)
  139. }
  140. func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool) {
  141. guard shouldUpdateButtonBarView else { return }
  142. buttonBarView.move(fromIndex: fromIndex, toIndex: toIndex, progressPercentage: progressPercentage, pagerScroll: .yes)
  143. if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
  144. let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex != fromIndex ? fromIndex : toIndex, section: 0)) as? ButtonBarCellType
  145. let newCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarCellType
  146. changeCurrentIndexProgressive(oldCell, newCell, progressPercentage, indexWasChanged, true)
  147. }
  148. }
  149. // MARK: - UICollectionViewDelegateFlowLayut
  150. @objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
  151. guard let cellWidthValue = cachedCellWidths?[indexPath.row] else {
  152. fatalError("cachedCellWidths for \(indexPath.row) must not be nil")
  153. }
  154. return CGSize(width: cellWidthValue, height: collectionView.frame.size.height)
  155. }
  156. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  157. guard indexPath.item != currentIndex else { return }
  158. buttonBarView.moveTo(index: indexPath.item, animated: true, swipeDirection: .none, pagerScroll: .yes)
  159. shouldUpdateButtonBarView = false
  160. let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarCellType
  161. let newCell = buttonBarView.cellForItem(at: IndexPath(item: indexPath.item, section: 0)) as? ButtonBarCellType
  162. if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
  163. changeCurrentIndexProgressive(oldCell, newCell, 1, true, true)
  164. }
  165. moveToViewController(at: indexPath.item)
  166. }
  167. // MARK: - UICollectionViewDataSource
  168. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  169. return viewControllers.count
  170. }
  171. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  172. guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: VLCLabelCell.cellIdentifier, for: indexPath) as? ButtonBarCellType else {
  173. fatalError("UICollectionViewCell should be or extend from ButtonBarViewCell")
  174. }
  175. let childController = viewControllers[indexPath.item] as! IndicatorInfoProvider // swiftlint:disable:this force_cast
  176. let indicatorInfo = childController.indicatorInfo(for: self)
  177. configure(cell: cell, for: indicatorInfo)
  178. if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
  179. changeCurrentIndexProgressive(currentIndex == indexPath.item ? nil : cell, currentIndex == indexPath.item ? cell : nil, 1, true, false)
  180. }
  181. return cell
  182. }
  183. // MARK: - UIScrollViewDelegate
  184. override func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
  185. super.scrollViewDidEndScrollingAnimation(scrollView)
  186. guard scrollView == containerView else { return }
  187. shouldUpdateButtonBarView = true
  188. }
  189. func configure(cell: ButtonBarCellType, for indicatorInfo: IndicatorInfo) {
  190. fatalError("You must override this method to set up ButtonBarView cell accordingly")
  191. }
  192. private func calculateWidths() -> [CGFloat] {
  193. let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout // swiftlint:disable:this force_cast
  194. let numberOfCells = viewControllers.count
  195. var minimumCellWidths = [CGFloat]()
  196. var collectionViewContentWidth: CGFloat = 0
  197. let indicatorWidth: CGFloat = 70.0
  198. viewControllers.forEach { _ in
  199. minimumCellWidths.append(indicatorWidth)
  200. collectionViewContentWidth += indicatorWidth
  201. }
  202. let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing
  203. collectionViewContentWidth += cellSpacingTotal
  204. let collectionViewAvailableVisibleWidth = buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right
  205. if collectionViewAvailableVisibleWidth < collectionViewContentWidth {
  206. return minimumCellWidths
  207. } else {
  208. let stretchedCellWidthIfAllEqual = (collectionViewAvailableVisibleWidth - cellSpacingTotal) / CGFloat(numberOfCells)
  209. let generalMinimumCellWidth = calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: stretchedCellWidthIfAllEqual, previousNumberOfLargeCells: 0)
  210. var stretchedCellWidths = [CGFloat]()
  211. for minimumCellWidthValue in minimumCellWidths {
  212. let cellWidth = (minimumCellWidthValue > generalMinimumCellWidth) ? minimumCellWidthValue : generalMinimumCellWidth
  213. stretchedCellWidths.append(cellWidth)
  214. }
  215. return stretchedCellWidths
  216. }
  217. }
  218. }
  219. // MARK: Protocols
  220. protocol IndicatorInfoProvider {
  221. func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo
  222. }
  223. protocol PagerTabStripIsProgressiveDelegate: class {
  224. func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool)
  225. }
  226. protocol PagerTabStripDataSource: class {
  227. func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController]
  228. }