ToastCenter.swift 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import UIKit
  2. open class ToastCenter: NSObject {
  3. // MARK: Properties
  4. private let queue: OperationQueue = {
  5. let queue = OperationQueue()
  6. queue.maxConcurrentOperationCount = 1
  7. return queue
  8. }()
  9. open var currentToast: Toast? {
  10. return self.queue.operations.first { !$0.isCancelled && !$0.isFinished } as? Toast
  11. }
  12. /// If this value is `true` and the user is using VoiceOver,
  13. /// VoiceOver will announce the text in the toast when `ToastView` is displayed.
  14. @objc public var isSupportAccessibility: Bool = true
  15. /// By default, queueing for toast is enabled.
  16. /// If this value is `false`, only the last requested toast will be shown.
  17. @objc public var isQueueEnabled: Bool = true
  18. @objc public static let `default` = ToastCenter()
  19. // MARK: Initializing
  20. override init() {
  21. super.init()
  22. #if swift(>=4.2)
  23. let name = UIDevice.orientationDidChangeNotification
  24. #else
  25. let name = NSNotification.Name.UIDeviceOrientationDidChange
  26. #endif
  27. NotificationCenter.default.addObserver(
  28. self,
  29. selector: #selector(self.deviceOrientationDidChange),
  30. name: name,
  31. object: nil
  32. )
  33. }
  34. // MARK: Adding Toasts
  35. open func add(_ toast: Toast) {
  36. if !isQueueEnabled {
  37. cancelAll()
  38. }
  39. self.queue.addOperation(toast)
  40. }
  41. // MARK: Cancelling Toasts
  42. @objc open func cancelAll() {
  43. queue.cancelAllOperations()
  44. }
  45. // MARK: Notifications
  46. @objc dynamic func deviceOrientationDidChange() {
  47. if let lastToast = self.queue.operations.first as? Toast {
  48. lastToast.view.setNeedsLayout()
  49. }
  50. }
  51. }