VLCActionSheet.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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 optional 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. setHeaderRoundedCorners()
  130. // This is to avoid a horrible visual glitch!
  131. mainStackView.isHidden = false
  132. let realMainStackView = mainStackView.frame
  133. mainStackView.frame.origin.y += mainStackView.frame.origin.y
  134. UIView.animate(withDuration: 0.65, delay: 0,
  135. usingSpringWithDamping: 0.8,
  136. initialSpringVelocity: 0,
  137. options: .curveEaseOut,
  138. animations: {
  139. [mainStackView, backgroundView] in
  140. mainStackView.frame = realMainStackView
  141. backgroundView.alpha = 1
  142. })
  143. }
  144. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  145. super.viewWillTransition(to: size, with: coordinator)
  146. coordinator.animate(alongsideTransition: { [weak self] _ in
  147. self?.maxCollectionViewHeightConstraint.constant = size.height / 2
  148. self?.collectionView.layoutIfNeeded()
  149. self?.setHeaderRoundedCorners()
  150. })
  151. }
  152. override func viewWillLayoutSubviews() {
  153. super.viewWillLayoutSubviews()
  154. collectionView.collectionViewLayout.invalidateLayout()
  155. }
  156. @objc fileprivate func updateTheme() {
  157. collectionView.backgroundColor = PresentationTheme.current.colors.background
  158. headerView.backgroundColor = PresentationTheme.current.colors.background
  159. headerView.title.textColor = PresentationTheme.current.colors.cellTextColor
  160. bottomBackgroundView.backgroundColor = PresentationTheme.current.colors.background
  161. for cell in collectionView.visibleCells {
  162. if let cell = cell as? VLCActionSheetCell {
  163. cell.backgroundColor = PresentationTheme.current.colors.background
  164. cell.name.textColor = PresentationTheme.current.colors.cellTextColor
  165. }
  166. }
  167. collectionView.layoutIfNeeded()
  168. }
  169. }
  170. // MARK: Private setup methods
  171. private extension VLCActionSheet {
  172. private func setuplHeaderViewConstraints() {
  173. NSLayoutConstraint.activate([
  174. headerView.heightAnchor.constraint(equalToConstant: cellHeight),
  175. headerView.widthAnchor.constraint(equalTo: view.widthAnchor),
  176. ])
  177. }
  178. private func setupCollectionViewConstraints() {
  179. NSLayoutConstraint.activate([
  180. collectionViewHeightConstraint,
  181. maxCollectionViewHeightConstraint,
  182. collectionView.widthAnchor.constraint(equalTo: view.widthAnchor),
  183. ])
  184. }
  185. private func setupBottomBackgroundView() {
  186. NSLayoutConstraint.activate([
  187. bottomBackgroundViewHeightConstraint,
  188. bottomBackgroundView.widthAnchor.constraint(equalTo: view.widthAnchor)
  189. ])
  190. }
  191. private func setupMainStackViewConstraints() {
  192. NSLayoutConstraint.activate([
  193. // Extra padding for spring animation
  194. mainStackView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 10),
  195. mainStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
  196. mainStackView.widthAnchor.constraint(equalTo: view.widthAnchor),
  197. mainStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
  198. ])
  199. }
  200. }
  201. // MARK: Helpers
  202. private extension VLCActionSheet {
  203. private func setHeaderRoundedCorners() {
  204. let roundedCornerPath = UIBezierPath(roundedRect: headerView.bounds, byRoundingCorners: [.topLeft, .topRight],
  205. cornerRadii: CGSize(width: 10, height: 10))
  206. let maskLayer = CAShapeLayer()
  207. maskLayer.path = roundedCornerPath.cgPath
  208. headerView.layer.mask = maskLayer
  209. }
  210. }
  211. // MARK: Actions
  212. extension VLCActionSheet {
  213. @objc func setAction(closure action: @escaping (_ item: Any) -> Void) {
  214. self.action = action
  215. }
  216. @objc func removeActionSheet() {
  217. let realMainStackView = mainStackView.frame
  218. UIView.animate(withDuration: 0.55, delay: 0,
  219. usingSpringWithDamping: 1,
  220. initialSpringVelocity: 0,
  221. options: .curveEaseIn,
  222. animations: {
  223. [mainStackView, backgroundView] in
  224. // Dismiss the mainStackView to the bottom of the screen
  225. mainStackView.frame.origin.y += mainStackView.frame.size.height
  226. backgroundView.alpha = 0
  227. }, completion: {
  228. [presentingViewController] finished in
  229. presentingViewController?.dismiss(animated: false,
  230. completion: {
  231. [unowned self] in
  232. // When everything is complete, reset the frame for the re-use
  233. self.mainStackView.frame = realMainStackView
  234. })
  235. })
  236. }
  237. }
  238. // MARK: UICollectionViewDelegateFlowLayout
  239. extension VLCActionSheet: UICollectionViewDelegateFlowLayout {
  240. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  241. return CGSize(width: collectionView.frame.width, height: cellHeight)
  242. }
  243. }
  244. // MARK: UICollectionViewDelegate
  245. extension VLCActionSheet: UICollectionViewDelegate {
  246. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  247. if let delegate = delegate, let item = delegate.itemAtIndexPath(indexPath) {
  248. delegate.actionSheet?(collectionView: collectionView, didSelectItem: item, At: indexPath)
  249. action?(item)
  250. }
  251. removeActionSheet()
  252. }
  253. }
  254. // MARK: UICollectionViewDataSource
  255. extension VLCActionSheet: UICollectionViewDataSource {
  256. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  257. if let dataSource = dataSource {
  258. return dataSource.numberOfRows()
  259. }
  260. preconditionFailure("VLCActionSheet: No data source")
  261. }
  262. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  263. if let dataSource = dataSource {
  264. return dataSource.actionSheet(collectionView: collectionView, cellForItemAt: indexPath)
  265. }
  266. preconditionFailure("VLCActionSheet: No data source")
  267. }
  268. }