NCEmptyDataSet.swift 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 numberItemsForSection: [Int:Int] = [:]
  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 numberOfSections(_ num: Int) {
  34. self.numberItemsForSection.removeAll()
  35. }
  36. func numberOfItemsInSection(_ num: Int, section: Int) {
  37. if let emptyView = emptyView {
  38. self.delegate?.emptyDataSetView?(emptyView)
  39. if !(timer?.isValid ?? false) && emptyView.isHidden == true {
  40. timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(timerHandler(_:)), userInfo: nil, repeats: false)
  41. }
  42. var numberItems: Int = 0
  43. for (_, value) in numberItemsForSection {
  44. numberItems += value
  45. }
  46. if numberItems > 0 {
  47. self.emptyView?.isHidden = true
  48. }
  49. numberItemsForSection[section] = num
  50. }
  51. }
  52. @objc func timerHandler(_ timer: Timer) {
  53. var numberItems: Int = 0
  54. for (_, value) in numberItemsForSection {
  55. numberItems += value
  56. }
  57. if numberItems == 0 {
  58. self.emptyView?.isHidden = false
  59. } else {
  60. self.emptyView?.isHidden = true
  61. }
  62. }
  63. }
  64. public class NCEmptyView: UIView {
  65. @IBOutlet weak var emptyImage: UIImageView!
  66. @IBOutlet weak var emptyTitle: UILabel!
  67. @IBOutlet weak var emptyDescription: UILabel!
  68. }