ActionSheet.swift 12 KB

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