VLCActionSheet.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. /*****************************************************************************
  2. * VLCActionSheet.swift
  3. *
  4. * Copyright © 2018 VLC authors and VideoLAN
  5. * Copyright © 2018 Videolabs
  6. *
  7. * Authors: Soomin Lee <bubu@mikan.io>
  8. *
  9. * Refer to the COPYING file of the official project for license.
  10. *****************************************************************************/
  11. import Foundation
  12. import UIKit
  13. @objc protocol VLCActionSheetDataSource {
  14. @objc func numberOfRows() -> Int
  15. @objc func actionSheet(collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
  16. }
  17. @objc protocol VLCActionSheetDelegate {
  18. @objc optional func headerViewTitle() -> String?
  19. @objc func itemAtIndexPath(_ indexPath: IndexPath) -> Any?
  20. @objc func actionSheet(collectionView: UICollectionView, didSelectItem item: Any, At indexPath: IndexPath)
  21. }
  22. // MARK: VLCActionSheet
  23. class VLCActionSheet: UIViewController {
  24. private let cellHeight: CGFloat = 50
  25. @objc weak var dataSource: VLCActionSheetDataSource?
  26. @objc weak var delegate: VLCActionSheetDelegate?
  27. var action: ((_ item: Any) -> Void)?
  28. lazy var backgroundView: UIView = {
  29. let backgroundView = UIView()
  30. backgroundView.alpha = 0
  31. backgroundView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
  32. backgroundView.backgroundColor = UIColor.black.withAlphaComponent(0.6)
  33. backgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.removeActionSheet)))
  34. return backgroundView
  35. }()
  36. lazy var collectionViewLayout: UICollectionViewFlowLayout = {
  37. let collectionViewLayout = UICollectionViewFlowLayout()
  38. collectionViewLayout.minimumLineSpacing = 1
  39. collectionViewLayout.minimumInteritemSpacing = 0
  40. return collectionViewLayout
  41. }()
  42. @objc lazy var collectionView: UICollectionView = {
  43. let collectionView = UICollectionView(frame: UIScreen.main.bounds, collectionViewLayout: collectionViewLayout)
  44. collectionView.delegate = self
  45. collectionView.dataSource = self
  46. collectionView.backgroundColor = PresentationTheme.current.colors.background
  47. collectionView.alwaysBounceVertical = true
  48. collectionView.showsVerticalScrollIndicator = false
  49. collectionView.register(VLCActionSheetCell.self, forCellWithReuseIdentifier: VLCActionSheetCell.identifier)
  50. collectionView.translatesAutoresizingMaskIntoConstraints = false
  51. return collectionView
  52. }()
  53. lazy var headerView: VLCActionSheetSectionHeader = {
  54. let headerView = VLCActionSheetSectionHeader()
  55. headerView.title.text = delegate?.headerViewTitle?() ?? "Default header title"
  56. headerView.title.textColor = PresentationTheme.current.colors.cellTextColor
  57. headerView.backgroundColor = PresentationTheme.current.colors.background
  58. headerView.translatesAutoresizingMaskIntoConstraints = false
  59. return headerView
  60. }()
  61. lazy var bottomBackgroundView: UIView = {
  62. let bottomBackgroundView = UIView()
  63. bottomBackgroundView.backgroundColor = PresentationTheme.current.colors.background
  64. bottomBackgroundView.translatesAutoresizingMaskIntoConstraints = false
  65. return bottomBackgroundView
  66. }()
  67. lazy var mainStackView: UIStackView = {
  68. let mainStackView = UIStackView()
  69. mainStackView.spacing = 0
  70. mainStackView.axis = .vertical
  71. mainStackView.alignment = .center
  72. mainStackView.translatesAutoresizingMaskIntoConstraints = false
  73. return mainStackView
  74. }()
  75. fileprivate lazy var maxCollectionViewHeightConstraint: NSLayoutConstraint = {
  76. let maxCollectionViewHeightConstraint = collectionView.heightAnchor.constraint(
  77. lessThanOrEqualToConstant: (view.bounds.height / 2) - cellHeight)
  78. return maxCollectionViewHeightConstraint
  79. }()
  80. fileprivate lazy var collectionViewHeightConstraint: NSLayoutConstraint = {
  81. guard let dataSource = dataSource else {
  82. preconditionFailure("VLCActionSheet: Data source not set correctly!")
  83. }
  84. let collectionViewHeightConstraint = collectionView.heightAnchor.constraint(
  85. equalToConstant: CGFloat(dataSource.numberOfRows()) * cellHeight)
  86. collectionViewHeightConstraint.priority = .required - 1
  87. return collectionViewHeightConstraint
  88. }()
  89. fileprivate lazy var bottomBackgroundViewHeightConstraint: NSLayoutConstraint = {
  90. let bottomBackgroundViewHeightConstraint = bottomBackgroundView.heightAnchor.constraint(equalToConstant: 0)
  91. return bottomBackgroundViewHeightConstraint
  92. }()
  93. override func updateViewConstraints() {
  94. super.updateViewConstraints()
  95. if let presentingViewController = presentingViewController, let dataSource = dataSource {
  96. collectionViewHeightConstraint.constant = CGFloat(dataSource.numberOfRows()) * cellHeight
  97. maxCollectionViewHeightConstraint.constant = presentingViewController.view.frame.size.height / 2
  98. collectionView.setNeedsLayout()
  99. collectionView.layoutIfNeeded()
  100. }
  101. }
  102. @available(iOS 11.0, *)
  103. override func viewSafeAreaInsetsDidChange() {
  104. bottomBackgroundViewHeightConstraint.constant = view.safeAreaInsets.bottom
  105. }
  106. // MARK: UIViewController
  107. override func viewDidLoad() {
  108. super.viewDidLoad()
  109. NotificationCenter.default.addObserver(self, selector: #selector(updateTheme), name: .VLCThemeDidChangeNotification, object: nil)
  110. view.addSubview(backgroundView)
  111. view.addSubview(mainStackView)
  112. mainStackView.addArrangedSubview(headerView)
  113. mainStackView.addArrangedSubview(collectionView)
  114. mainStackView.addArrangedSubview(bottomBackgroundView)
  115. backgroundView.frame = UIScreen.main.bounds
  116. setupMainStackViewConstraints()
  117. setupCollectionViewConstraints()
  118. setuplHeaderViewConstraints()
  119. setupBottomBackgroundView()
  120. }
  121. override func viewWillAppear(_ animated: Bool) {
  122. super.viewWillAppear(animated)
  123. mainStackView.isHidden = true
  124. collectionView.reloadData()
  125. updateViewConstraints()
  126. }
  127. override func viewDidAppear(_ animated: Bool) {
  128. super.viewDidAppear(animated)
  129. // This is to avoid a horrible visual glitch!
  130. mainStackView.isHidden = false
  131. let roundedCornerPath = UIBezierPath(roundedRect: headerView.bounds, byRoundingCorners: [.topLeft, .topRight],
  132. cornerRadii: CGSize(width: 10, height: 10))
  133. let maskLayer = CAShapeLayer()
  134. maskLayer.path = roundedCornerPath.cgPath
  135. headerView.layer.mask = maskLayer
  136. let realMainStackView = mainStackView.frame
  137. mainStackView.frame.origin.y += mainStackView.frame.origin.y
  138. UIView.animate(withDuration: 0.65, delay: 0,
  139. usingSpringWithDamping: 0.8,
  140. initialSpringVelocity: 0,
  141. options: .curveEaseOut,
  142. animations: {
  143. [mainStackView, backgroundView] in
  144. mainStackView.frame = realMainStackView
  145. backgroundView.alpha = 1
  146. })
  147. }
  148. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  149. super.viewWillTransition(to: size, with: coordinator)
  150. coordinator.animate(alongsideTransition: { [weak self] _ in
  151. self?.maxCollectionViewHeightConstraint.constant = size.height / 2
  152. self?.collectionView.layoutIfNeeded()
  153. })
  154. }
  155. override func viewWillLayoutSubviews() {
  156. super.viewWillLayoutSubviews()
  157. collectionView.collectionViewLayout.invalidateLayout()
  158. }
  159. @objc fileprivate func updateTheme() {
  160. collectionView.backgroundColor = PresentationTheme.current.colors.background
  161. headerView.backgroundColor = PresentationTheme.current.colors.background
  162. headerView.title.textColor = PresentationTheme.current.colors.cellTextColor
  163. bottomBackgroundView.backgroundColor = PresentationTheme.current.colors.background
  164. for cell in collectionView.visibleCells {
  165. if let cell = cell as? VLCActionSheetCell {
  166. cell.backgroundColor = PresentationTheme.current.colors.background
  167. cell.name.textColor = PresentationTheme.current.colors.cellTextColor
  168. }
  169. }
  170. collectionView.layoutIfNeeded()
  171. }
  172. }
  173. // MARK: Private setup methods
  174. private extension VLCActionSheet {
  175. private func setuplHeaderViewConstraints() {
  176. NSLayoutConstraint.activate([
  177. headerView.heightAnchor.constraint(equalToConstant: cellHeight),
  178. headerView.widthAnchor.constraint(equalTo: view.widthAnchor),
  179. ])
  180. }
  181. private func setupCollectionViewConstraints() {
  182. NSLayoutConstraint.activate([
  183. collectionViewHeightConstraint,
  184. maxCollectionViewHeightConstraint,
  185. collectionView.widthAnchor.constraint(equalTo: view.widthAnchor),
  186. ])
  187. }
  188. private func setupBottomBackgroundView() {
  189. NSLayoutConstraint.activate([
  190. bottomBackgroundViewHeightConstraint,
  191. bottomBackgroundView.widthAnchor.constraint(equalTo: view.widthAnchor)
  192. ])
  193. }
  194. private func setupMainStackViewConstraints() {
  195. NSLayoutConstraint.activate([
  196. // Extra padding for spring animation
  197. mainStackView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 10),
  198. mainStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
  199. mainStackView.widthAnchor.constraint(equalTo: view.widthAnchor),
  200. mainStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
  201. ])
  202. }
  203. }
  204. // MARK: Actions
  205. extension VLCActionSheet {
  206. @objc func setAction(closure action: @escaping (_ item: Any) -> Void) {
  207. self.action = action
  208. }
  209. @objc func removeActionSheet() {
  210. let realMainStackView = mainStackView.frame
  211. UIView.animate(withDuration: 0.55, delay: 0,
  212. usingSpringWithDamping: 1,
  213. initialSpringVelocity: 0,
  214. options: .curveEaseIn,
  215. animations: {
  216. [mainStackView, backgroundView] in
  217. // Dismiss the mainStackView to the bottom of the screen
  218. mainStackView.frame.origin.y += mainStackView.frame.size.height
  219. backgroundView.alpha = 0
  220. }, completion: {
  221. [presentingViewController] finished in
  222. presentingViewController?.dismiss(animated: false,
  223. completion: {
  224. [unowned self] in
  225. // When everything is complete, reset the frame for the re-use
  226. self.mainStackView.frame = realMainStackView
  227. })
  228. })
  229. }
  230. }
  231. // MARK: UICollectionViewDelegateFlowLayout
  232. extension VLCActionSheet: UICollectionViewDelegateFlowLayout {
  233. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  234. return CGSize(width: collectionView.frame.width, height: cellHeight)
  235. }
  236. }
  237. // MARK: UICollectionViewDelegate
  238. extension VLCActionSheet: UICollectionViewDelegate {
  239. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  240. if let delegate = delegate, let item = delegate.itemAtIndexPath(indexPath) {
  241. delegate.actionSheet(collectionView: collectionView, didSelectItem: item, At: indexPath)
  242. action?(item)
  243. }
  244. removeActionSheet()
  245. }
  246. }
  247. // MARK: UICollectionViewDataSource
  248. extension VLCActionSheet: UICollectionViewDataSource {
  249. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  250. if let dataSource = dataSource {
  251. return dataSource.numberOfRows()
  252. }
  253. preconditionFailure("VLCActionSheet: No data source")
  254. }
  255. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  256. if let dataSource = dataSource {
  257. return dataSource.actionSheet(collectionView: collectionView, cellForItemAt: indexPath)
  258. }
  259. preconditionFailure("VLCActionSheet: No data source")
  260. }
  261. }