ActionSheet.swift 13 KB

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