NCEmptyDataSet.swift 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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] = []
  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. numberItemsForSection = [Int](repeating: 0, count:1)
  23. emptyView.frame = CGRect(x:0, y: 0, width:300, height:300)
  24. emptyView.isHidden = true
  25. emptyView.translatesAutoresizingMaskIntoConstraints = false
  26. emptyView.emptyTitle.sizeToFit()
  27. emptyView.emptyDescription.sizeToFit()
  28. view.addSubview(emptyView)
  29. let constantY: CGFloat = (view.frame.height - emptyView.frame.height) / 2 - offset
  30. emptyView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
  31. emptyView.topAnchor.constraint(equalTo: view.topAnchor, constant: constantY).isActive = true
  32. }
  33. }
  34. func numberOfSections(_ num: Int) {
  35. numberItemsForSection = [Int](repeating: 0, count:num)
  36. }
  37. func numberOfItemsInSection(_ num: Int, section: Int) {
  38. if let emptyView = emptyView {
  39. self.delegate?.emptyDataSetView?(emptyView)
  40. if !(timer?.isValid ?? false) && emptyView.isHidden == true {
  41. timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(timerHandler(_:)), userInfo: nil, repeats: false)
  42. }
  43. var numberItems: Int = 0
  44. for value in numberItemsForSection {
  45. numberItems += value
  46. }
  47. if numberItems > 0 {
  48. self.emptyView?.isHidden = true
  49. }
  50. numberItemsForSection[section] = num
  51. }
  52. }
  53. @objc func timerHandler(_ timer: Timer) {
  54. var numberItems: Int = 0
  55. for value in numberItemsForSection {
  56. numberItems += value
  57. }
  58. if numberItems == 0 {
  59. self.emptyView?.isHidden = false
  60. } else {
  61. self.emptyView?.isHidden = true
  62. }
  63. }
  64. }
  65. public class NCEmptyView: UIView {
  66. @IBOutlet weak var emptyImage: UIImageView!
  67. @IBOutlet weak var emptyTitle: UILabel!
  68. @IBOutlet weak var emptyDescription: UILabel!
  69. }