HomeViewController.swift 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. //
  2. // HomeViewController.swift
  3. // AIPaint
  4. //
  5. // Created by Fengyu He on 2022/11/29.
  6. //
  7. import UIKit
  8. import SnapKit
  9. import CoreData
  10. class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
  11. lazy var paintingTableView: UITableView = {
  12. let tableView = UITableView()
  13. tableView.separatorStyle = .singleLine
  14. tableView.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
  15. tableView.allowsSelection = true
  16. tableView.allowsMultipleSelection = false
  17. return tableView
  18. }()
  19. var delegate: AppDelegate?
  20. var context: NSManagedObjectContext?
  21. var fetchPainting: NSFetchRequest<Painting>?
  22. var info: [Painting] = []
  23. override func viewDidLoad() {
  24. super.viewDidLoad()
  25. if UITraitCollection.current.userInterfaceStyle == .dark {
  26. view.backgroundColor = .black
  27. } else {
  28. view.backgroundColor = .white
  29. }
  30. self.title = "作品"
  31. delegate = UIApplication.shared.delegate as? AppDelegate
  32. context = delegate!.persistentContainer.viewContext
  33. fetchPainting = NSFetchRequest<Painting>.init(entityName: "Painting")
  34. paintingTableView.delegate = self
  35. paintingTableView.dataSource = self
  36. view.addSubview(paintingTableView)
  37. paintingTableView.snp.makeConstraints { (make) in
  38. make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
  39. make.width.equalTo(view.safeAreaLayoutGuide.snp.width)
  40. make.height.equalTo(view.safeAreaLayoutGuide.snp.height)
  41. make.centerX.equalTo(view.safeAreaLayoutGuide.snp.centerX)
  42. }
  43. }
  44. override func viewWillAppear(_ animated: Bool) {
  45. do {
  46. let paintings = try context?.fetch(fetchPainting!)
  47. for painting in paintings! {
  48. if !info.contains(painting) {
  49. info.append(painting)
  50. } else {
  51. }
  52. }
  53. } catch {}
  54. paintingTableView.reloadData()
  55. }
  56. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  57. print("info loaded \(info.count)")
  58. return info.count
  59. }
  60. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  61. let cell = PaintingCell(style: .default, reuseIdentifier: "PaintingCell")
  62. cell.setValueForCell(painting: info[indexPath.row])
  63. return cell
  64. }
  65. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  66. return 100
  67. }
  68. }