NCEmptyDataSet.swift 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. init(view: UIView, image: UIImage?, title: String, description: String, offset: CGFloat = 0, delegate: NCEmptyDataSetDelegate?) {
  16. super.init()
  17. if let emptyView = UINib(nibName: "NCEmptyView", bundle: nil).instantiate(withOwner: self, options: nil).first as? NCEmptyView {
  18. self.delegate = delegate
  19. self.emptyView = emptyView
  20. emptyView.frame = CGRect(x:0, y: 0, width:300, height:300)
  21. emptyView.isHidden = true
  22. emptyView.translatesAutoresizingMaskIntoConstraints = false
  23. emptyView.emptyImage.image = image
  24. emptyView.emptyTitle.text = NSLocalizedString(title, comment: "")
  25. emptyView.emptyTitle.sizeToFit()
  26. emptyView.emptyDescription.text = NSLocalizedString(description, comment: "")
  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 numberOfItemsInSection(_ numberItems: Int) {
  35. if let emptyView = emptyView {
  36. self.delegate?.emptyDataSetView?(emptyView)
  37. }
  38. if numberItems == 0 {
  39. DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
  40. self.emptyView?.isHidden = false
  41. }
  42. } else {
  43. DispatchQueue.main.asyncAfter(deadline: .now() + 0.0) {
  44. self.emptyView?.isHidden = true
  45. }
  46. }
  47. }
  48. }
  49. public class NCEmptyView: UIView {
  50. @IBOutlet weak var emptyImage: UIImageView!
  51. @IBOutlet weak var emptyTitle: UILabel!
  52. @IBOutlet weak var emptyDescription: UILabel!
  53. }