NCEmptyDataSet.swift 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. //
  2. // NCEmptyDataSet.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 19/10/2020.
  6. // Copyright © 2020 Marino Faggiana. All rights reserved.
  7. //
  8. import Foundation
  9. @objc public protocol NCEmptyDataSetDelegate {
  10. @objc optional func emptyDataSetView(_ view: NCEmptyView)
  11. }
  12. class NCEmptyDataSet: NSObject {
  13. var emptyView: NCEmptyView?
  14. var delegate: NCEmptyDataSetDelegate?
  15. var timer: Timer?
  16. var numberItemsForSections: Int = 0
  17. init(view: UIView, offset: CGFloat = 0, delegate: NCEmptyDataSetDelegate?) {
  18. super.init()
  19. if let emptyView = UINib(nibName: "NCEmptyView", bundle: nil).instantiate(withOwner: self, options: nil).first as? NCEmptyView {
  20. self.delegate = delegate
  21. self.emptyView = emptyView
  22. emptyView.frame = CGRect(x:0, y: 0, width:300, height:300)
  23. emptyView.isHidden = true
  24. emptyView.translatesAutoresizingMaskIntoConstraints = false
  25. emptyView.emptyTitle.sizeToFit()
  26. emptyView.emptyDescription.sizeToFit()
  27. view.addSubview(emptyView)
  28. let constantY: CGFloat = (view.frame.height - emptyView.frame.height) / 2 - offset
  29. emptyView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
  30. emptyView.topAnchor.constraint(equalTo: view.topAnchor, constant: constantY).isActive = true
  31. }
  32. }
  33. func numberOfItemsInSection(_ num: Int, section: Int) {
  34. if section == 0 {
  35. numberItemsForSections = num
  36. } else {
  37. numberItemsForSections = numberItemsForSections + num
  38. }
  39. if let emptyView = emptyView {
  40. self.delegate?.emptyDataSetView?(emptyView)
  41. if !(timer?.isValid ?? false) && emptyView.isHidden == true {
  42. timer = Timer.scheduledTimer(timeInterval: 0.3, target: self, selector: #selector(timerHandler(_:)), userInfo: nil, repeats: false)
  43. }
  44. if numberItemsForSections > 0 {
  45. self.emptyView?.isHidden = true
  46. }
  47. }
  48. }
  49. @objc func timerHandler(_ timer: Timer) {
  50. if numberItemsForSections == 0 {
  51. self.emptyView?.isHidden = false
  52. } else {
  53. self.emptyView?.isHidden = true
  54. }
  55. }
  56. }
  57. public class NCEmptyView: UIView {
  58. @IBOutlet weak var emptyImage: UIImageView!
  59. @IBOutlet weak var emptyTitle: UILabel!
  60. @IBOutlet weak var emptyDescription: UILabel!
  61. public override func awakeFromNib() {
  62. super.awakeFromNib()
  63. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  64. changeTheming()
  65. }
  66. @objc func changeTheming() {
  67. emptyTitle.textColor = NCBrandColor.sharedInstance.textView
  68. }
  69. }