BaseButtonBarPagerTabStripViewController.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. @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. public 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 flowLayout = UICollectionViewFlowLayout()
  52. flowLayout.scrollDirection = .horizontal
  53. buttonBarView = ButtonBarView(frame: .zero, collectionViewLayout: flowLayout)
  54. buttonBarView.translatesAutoresizingMaskIntoConstraints = false
  55. view.addSubview(buttonBarView)
  56. NSLayoutConstraint.activate([
  57. buttonBarView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor),
  58. buttonBarView.rightAnchor.constraint(equalTo: view.rightAnchor),
  59. buttonBarView.leftAnchor.constraint(equalTo: view.leftAnchor),
  60. buttonBarView.heightAnchor.constraint(equalToConstant: 35)
  61. ])
  62. NSLayoutConstraint.activate([
  63. containerView.topAnchor.constraint(equalTo: buttonBarView.bottomAnchor),
  64. containerView.rightAnchor.constraint(equalTo: view.rightAnchor),
  65. containerView.leftAnchor.constraint(equalTo: view.leftAnchor),
  66. containerView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
  67. ]
  68. )
  69. buttonBarView.delegate = self
  70. buttonBarView.dataSource = self
  71. // register button bar item cell
  72. buttonBarView.register(UINib(nibName: "VLCLabelCell", bundle: .main), forCellWithReuseIdentifier:"Cell")
  73. }
  74. open override func viewWillAppear(_ animated: Bool) {
  75. super.viewWillAppear(animated)
  76. buttonBarView.layoutIfNeeded()
  77. isViewAppearing = true
  78. }
  79. open override func viewDidAppear(_ animated: Bool) {
  80. super.viewDidAppear(animated)
  81. isViewAppearing = false
  82. }
  83. open override func viewDidLayoutSubviews() {
  84. super.viewDidLayoutSubviews()
  85. guard isViewAppearing || isViewRotating else { return }
  86. // Force the UICollectionViewFlowLayout to get laid out again with the new size if
  87. // a) The view is appearing. This ensures that
  88. // collectionView:layout:sizeForItemAtIndexPath: is called for a second time
  89. // when the view is shown and when the view *frame(s)* are actually set
  90. // (we need the view frame's to have been set to work out the size's and on the
  91. // first call to collectionView:layout:sizeForItemAtIndexPath: the view frame(s)
  92. // aren't set correctly)
  93. // b) The view is rotating. This ensures that
  94. // collectionView:layout:sizeForItemAtIndexPath: is called again and can use the views
  95. // *new* frame so that the buttonBarView cell's actually get resized correctly
  96. cachedCellWidths = calculateWidths()
  97. buttonBarView.collectionViewLayout.invalidateLayout()
  98. // When the view first appears or is rotated we also need to ensure that the barButtonView's
  99. // selectedBar is resized and its contentOffset/scroll is set correctly (the selected
  100. // tab/cell may end up either skewed or off screen after a rotation otherwise)
  101. buttonBarView.moveTo(index: currentIndex, animated: false, swipeDirection: .none, pagerScroll: .scrollOnlyIfOutOfScreen)
  102. buttonBarView.selectItem(at: IndexPath(item: currentIndex, section: 0), animated: false, scrollPosition: [])
  103. }
  104. // MARK: - Public Methods
  105. open override func reloadPagerTabStripView() {
  106. super.reloadPagerTabStripView()
  107. guard isViewLoaded else { return }
  108. buttonBarView.reloadData()
  109. cachedCellWidths = calculateWidths()
  110. buttonBarView.moveTo(index: currentIndex, animated: false, swipeDirection: .none, pagerScroll: .yes)
  111. }
  112. open func calculateStretchedCellWidths(_ minimumCellWidths: [CGFloat], suggestedStretchedCellWidth: CGFloat, previousNumberOfLargeCells: Int) -> CGFloat {
  113. var numberOfLargeCells = 0
  114. var totalWidthOfLargeCells: CGFloat = 0
  115. for minimumCellWidthValue in minimumCellWidths where minimumCellWidthValue > suggestedStretchedCellWidth {
  116. totalWidthOfLargeCells += minimumCellWidthValue
  117. numberOfLargeCells += 1
  118. }
  119. guard numberOfLargeCells > previousNumberOfLargeCells else { return suggestedStretchedCellWidth }
  120. let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout // swiftlint:disable:this force_cast
  121. let collectionViewAvailiableWidth = buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right
  122. let numberOfCells = minimumCellWidths.count
  123. let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing
  124. let numberOfSmallCells = numberOfCells - numberOfLargeCells
  125. let newSuggestedStretchedCellWidth = (collectionViewAvailiableWidth - totalWidthOfLargeCells - cellSpacingTotal) / CGFloat(numberOfSmallCells)
  126. return calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: newSuggestedStretchedCellWidth, previousNumberOfLargeCells: numberOfLargeCells)
  127. }
  128. open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int) {
  129. guard shouldUpdateButtonBarView else { return }
  130. buttonBarView.moveTo(index: toIndex, animated: true, swipeDirection: toIndex < fromIndex ? .right : .left, pagerScroll: .yes)
  131. }
  132. open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool) {
  133. guard shouldUpdateButtonBarView else { return }
  134. buttonBarView.move(fromIndex: fromIndex, toIndex: toIndex, progressPercentage: progressPercentage, pagerScroll: .yes)
  135. if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
  136. let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex != fromIndex ? fromIndex : toIndex, section: 0)) as? ButtonBarCellType
  137. let newCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarCellType
  138. changeCurrentIndexProgressive(oldCell, newCell, progressPercentage, indexWasChanged, true)
  139. }
  140. }
  141. // MARK: - UICollectionViewDelegateFlowLayut
  142. @objc open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
  143. guard let cellWidthValue = cachedCellWidths?[indexPath.row] else {
  144. fatalError("cachedCellWidths for \(indexPath.row) must not be nil")
  145. }
  146. return CGSize(width: cellWidthValue, height: collectionView.frame.size.height)
  147. }
  148. open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  149. guard indexPath.item != currentIndex else { return }
  150. buttonBarView.moveTo(index: indexPath.item, animated: true, swipeDirection: .none, pagerScroll: .yes)
  151. shouldUpdateButtonBarView = false
  152. let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarCellType
  153. let newCell = buttonBarView.cellForItem(at: IndexPath(item: indexPath.item, section: 0)) as? ButtonBarCellType
  154. if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
  155. changeCurrentIndexProgressive(oldCell, newCell, 1, true, true)
  156. }
  157. moveToViewController(at: indexPath.item)
  158. }
  159. // MARK: - UICollectionViewDataSource
  160. open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  161. return viewControllers.count
  162. }
  163. open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  164. guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? ButtonBarCellType else {
  165. fatalError("UICollectionViewCell should be or extend from ButtonBarViewCell")
  166. }
  167. let childController = viewControllers[indexPath.item] as! IndicatorInfoProvider // swiftlint:disable:this force_cast
  168. let indicatorInfo = childController.indicatorInfo(for: self)
  169. configure(cell: cell, for: indicatorInfo)
  170. if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
  171. changeCurrentIndexProgressive(currentIndex == indexPath.item ? nil : cell, currentIndex == indexPath.item ? cell : nil, 1, true, false)
  172. }
  173. return cell
  174. }
  175. // MARK: - UIScrollViewDelegate
  176. open override func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
  177. super.scrollViewDidEndScrollingAnimation(scrollView)
  178. guard scrollView == containerView else { return }
  179. shouldUpdateButtonBarView = true
  180. }
  181. open func configure(cell: ButtonBarCellType, for indicatorInfo: IndicatorInfo) {
  182. fatalError("You must override this method to set up ButtonBarView cell accordingly")
  183. }
  184. private func calculateWidths() -> [CGFloat] {
  185. let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout // swiftlint:disable:this force_cast
  186. let numberOfCells = viewControllers.count
  187. var minimumCellWidths = [CGFloat]()
  188. var collectionViewContentWidth: CGFloat = 0
  189. let indicatorWidth: CGFloat = 70.0
  190. viewControllers.forEach { _ in
  191. minimumCellWidths.append(indicatorWidth)
  192. collectionViewContentWidth += indicatorWidth
  193. }
  194. let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing
  195. collectionViewContentWidth += cellSpacingTotal
  196. let collectionViewAvailableVisibleWidth = buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right
  197. if collectionViewAvailableVisibleWidth < collectionViewContentWidth {
  198. return minimumCellWidths
  199. } else {
  200. let stretchedCellWidthIfAllEqual = (collectionViewAvailableVisibleWidth - cellSpacingTotal) / CGFloat(numberOfCells)
  201. let generalMinimumCellWidth = calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: stretchedCellWidthIfAllEqual, previousNumberOfLargeCells: 0)
  202. var stretchedCellWidths = [CGFloat]()
  203. for minimumCellWidthValue in minimumCellWidths {
  204. let cellWidth = (minimumCellWidthValue > generalMinimumCellWidth) ? minimumCellWidthValue : generalMinimumCellWidth
  205. stretchedCellWidths.append(cellWidth)
  206. }
  207. return stretchedCellWidths
  208. }
  209. }
  210. private var shouldUpdateButtonBarView = true
  211. }
  212. // MARK: Protocols
  213. public protocol IndicatorInfoProvider {
  214. func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo
  215. }
  216. public protocol PagerTabStripIsProgressiveDelegate: class {
  217. func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool)
  218. }
  219. public protocol PagerTabStripDataSource: class {
  220. func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController]
  221. }