VLCActionSheet.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. @objc func removeActionSheet() {
  94. let realMainStackView = mainStackView.frame
  95. UIView.animate(withDuration: 0.55, delay: 0,
  96. usingSpringWithDamping: 1,
  97. initialSpringVelocity: 0,
  98. options: .curveEaseIn,
  99. animations: {
  100. [mainStackView, backgroundView] in
  101. // Dismiss the mainStackView to the bottom of the screen
  102. mainStackView.frame.origin.y += mainStackView.frame.size.height
  103. backgroundView.alpha = 0
  104. }, completion: {
  105. [presentingViewController] finished in
  106. presentingViewController?.dismiss(animated: false,
  107. completion: {
  108. [unowned self] in
  109. // When everything is complete, reset the frame for the re-use
  110. self.mainStackView.frame = realMainStackView
  111. })
  112. })
  113. }
  114. // MARK: Private methods
  115. fileprivate func setuplHeaderViewConstraints() {
  116. NSLayoutConstraint.activate([
  117. headerView.heightAnchor.constraint(equalToConstant: cellHeight),
  118. headerView.widthAnchor.constraint(equalTo: view.widthAnchor),
  119. ])
  120. }
  121. fileprivate func setupCollectionViewConstraints() {
  122. NSLayoutConstraint.activate([
  123. collectionViewHeightConstraint,
  124. maxCollectionViewHeightConstraint,
  125. collectionView.widthAnchor.constraint(equalTo: view.widthAnchor),
  126. ])
  127. }
  128. fileprivate func setupBottomBackgroundView() {
  129. NSLayoutConstraint.activate([
  130. bottomBackgroundViewHeightConstraint,
  131. bottomBackgroundView.widthAnchor.constraint(equalTo: view.widthAnchor)
  132. ])
  133. }
  134. fileprivate func setupMainStackViewConstraints() {
  135. NSLayoutConstraint.activate([
  136. mainStackView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 10),
  137. mainStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
  138. mainStackView.widthAnchor.constraint(equalTo: view.widthAnchor),
  139. mainStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
  140. ])
  141. }
  142. override func updateViewConstraints() {
  143. super.updateViewConstraints()
  144. if let presentingViewController = presentingViewController, let dataSource = dataSource {
  145. collectionViewHeightConstraint.constant = CGFloat(dataSource.numberOfRows()) * cellHeight
  146. maxCollectionViewHeightConstraint.constant = presentingViewController.view.frame.size.height / 2
  147. collectionView.setNeedsLayout()
  148. collectionView.layoutIfNeeded()
  149. }
  150. }
  151. @available(iOS 11.0, *)
  152. override func viewSafeAreaInsetsDidChange() {
  153. bottomBackgroundViewHeightConstraint.constant = view.safeAreaInsets.bottom
  154. }
  155. // MARK: UIViewController
  156. override func viewDidLoad() {
  157. super.viewDidLoad()
  158. NotificationCenter.default.addObserver(self, selector: #selector(updateTheme), name: .VLCThemeDidChangeNotification, object: nil)
  159. view.addSubview(backgroundView)
  160. view.addSubview(mainStackView)
  161. mainStackView.addArrangedSubview(headerView)
  162. mainStackView.addArrangedSubview(collectionView)
  163. mainStackView.addArrangedSubview(bottomBackgroundView)
  164. backgroundView.frame = UIScreen.main.bounds
  165. setupMainStackViewConstraints()
  166. setupCollectionViewConstraints()
  167. setuplHeaderViewConstraints()
  168. setupBottomBackgroundView()
  169. }
  170. override func viewWillAppear(_ animated: Bool) {
  171. super.viewWillAppear(animated)
  172. mainStackView.isHidden = true
  173. collectionView.reloadData()
  174. updateViewConstraints()
  175. }
  176. override func viewDidAppear(_ animated: Bool) {
  177. super.viewDidAppear(animated)
  178. // This is to avoid a horrible visual glitch!
  179. mainStackView.isHidden = false
  180. let roundedCornerPath = UIBezierPath(roundedRect: headerView.bounds, byRoundingCorners: [.topLeft, .topRight],
  181. cornerRadii: CGSize(width: 10, height: 10))
  182. let maskLayer = CAShapeLayer()
  183. maskLayer.path = roundedCornerPath.cgPath
  184. headerView.layer.mask = maskLayer
  185. let realMainStackView = mainStackView.frame
  186. mainStackView.frame.origin.y += mainStackView.frame.origin.y
  187. UIView.animate(withDuration: 0.65, delay: 0,
  188. usingSpringWithDamping: 0.8,
  189. initialSpringVelocity: 0,
  190. options: .curveEaseOut,
  191. animations: {
  192. [mainStackView, backgroundView] in
  193. mainStackView.frame = realMainStackView
  194. backgroundView.alpha = 1
  195. })
  196. }
  197. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  198. super.viewWillTransition(to: size, with: coordinator)
  199. coordinator.animate(alongsideTransition: { [weak self] _ in
  200. self?.maxCollectionViewHeightConstraint.constant = size.height / 2
  201. self?.collectionView.layoutIfNeeded()
  202. })
  203. }
  204. override func viewWillLayoutSubviews() {
  205. super.viewWillLayoutSubviews()
  206. collectionView.collectionViewLayout.invalidateLayout()
  207. }
  208. @objc func setAction(closure action: @escaping (_ item: Any) -> Void) {
  209. self.action = action
  210. }
  211. @objc fileprivate func updateTheme() {
  212. collectionView.backgroundColor = PresentationTheme.current.colors.background
  213. headerView.backgroundColor = PresentationTheme.current.colors.background
  214. headerView.title.textColor = PresentationTheme.current.colors.cellTextColor
  215. bottomBackgroundView.backgroundColor = PresentationTheme.current.colors.background
  216. for cell in collectionView.visibleCells {
  217. if let cell = cell as? VLCActionSheetCell {
  218. cell.backgroundColor = PresentationTheme.current.colors.background
  219. cell.name.textColor = PresentationTheme.current.colors.cellTextColor
  220. }
  221. }
  222. collectionView.layoutIfNeeded()
  223. }
  224. }
  225. // MARK: UICollectionViewDelegateFlowLayout
  226. extension VLCActionSheet: UICollectionViewDelegateFlowLayout {
  227. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  228. return CGSize(width: collectionView.frame.width, height: cellHeight)
  229. }
  230. }
  231. // MARK: UICollectionViewDelegate
  232. extension VLCActionSheet: UICollectionViewDelegate {
  233. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  234. if let delegate = delegate, let item = delegate.itemAtIndexPath(indexPath) {
  235. delegate.actionSheet(collectionView: collectionView, didSelectItem: item, At: indexPath)
  236. action?(item)
  237. }
  238. removeActionSheet()
  239. }
  240. }
  241. // MARK: UICollectionViewDataSource
  242. extension VLCActionSheet: UICollectionViewDataSource {
  243. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  244. if let dataSource = dataSource {
  245. return dataSource.numberOfRows()
  246. }
  247. preconditionFailure("VLCActionSheet: No data source")
  248. }
  249. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  250. if let dataSource = dataSource {
  251. return dataSource.actionSheet(collectionView: collectionView, cellForItemAt: indexPath)
  252. }
  253. preconditionFailure("VLCActionSheet: No data source")
  254. }
  255. }