BaseButtonBarPagerTabStripViewController.swift 13 KB

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