ActionSheet.swift 12 KB

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