ActionSheet.swift 13 KB

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