VLCActionSheet.swift 13 KB

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