UITableView的单元格根本不显示

时间:2018-10-19 06:35:36

标签: swift uitableview

没有显示UITableView的单元格。 可能的原因似乎是UITableView的委托和dataSource设置的一部分,但我不知道具体的地方。 因此,粘贴所有代码。 如果您不明白问题的意图,请随时告诉我。 我会告诉你真诚的。

import UIKit
import Firebase
import FirebaseStorage
import FirebaseFirestore
import SDWebImage

struct CellData {
  var date: Date
  var time: String
  var title: String
  var name: String
  var image: URL
}

struct TableSection<SectionItem: Comparable&Hashable, RowItem>: Comparable {
  var sectionItem: SectionItem
  var rowItems: [RowItem]

  static func < (lhs: TableSection, rhs: TableSection) -> Bool {
    return lhs.sectionItem > rhs.sectionItem
  }

  static func == (lhs: TableSection, rhs: TableSection) -> Bool {
    return lhs.sectionItem == rhs.sectionItem
  }

  static func group(rowItems : [RowItem], by criteria : (RowItem) -> SectionItem ) -> [TableSection<SectionItem, RowItem>] {
    let groups = Dictionary(grouping: rowItems, by: criteria)
    return groups.map(TableSection.init(sectionItem:rowItems:)).sorted()
  }
}

fileprivate func parseDate(_ str: String) -> Date {
  let dateFormat = DateFormatter()
  dateFormat.dateFormat = "yyyy年MM月dd日"
  return dateFormat.date(from: str)!
}

fileprivate func firstDayOfMonth(date: Date) -> Date {
  let calendar = Calendar.current
  let components = calendar.dateComponents([.year, .month, .day], from: date)
  return calendar.date(from: components)!
}





class timelineViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{

var arr = [CellData]()

let db = Firestore.firestore()

var sections = [TableSection<Date, CellData>]()

var teamIDFromFirebase: String = ""

var fireAuthUID = (Auth.auth().currentUser?.uid ?? "no data")

var dataImageFromFirestore = [Any]()

var dataTitleFromFireStore = [Any]()

var dataTimeFromFirestore = [Any]()

var dataNameFromFireStore = [Any]()

var dataDateFromFiewstore = [Any]()

var timelineDocumentIdArr = [Any]()

var draftDocumentIdArr = [Any]()

var submitDocumentIdArr = [Any]()

var selectedNum = 0


@IBOutlet weak var circleButton: UIButton!

@IBOutlet weak var userTable: UITableView!


override func viewDidLoad() {
    super.viewDidLoad()

    circleButton = Circle()

    if arr != nil {
        self.arr = []
        self.dataNameFromFireStore = [Any]()
        self.dataTimeFromFirestore = [Any]()
        self.dataTitleFromFireStore = [Any]()
        self.dataImageFromFirestore = [Any]()
        self.submitDocumentIdArr = [Any]()

        self.selectedNum = 1

        userTable.delegate = self
        userTable.dataSource = self

        userTable.register(UINib(nibName: "userTableViewCell", bundle: nil), forCellReuseIdentifier: "cellName")

        self.db.collection("users").document(self.fireAuthUID).addSnapshotListener { (snapshot3, error) in
            guard let document3 = snapshot3 else {
                print("erorr2 \(String(describing: error))")
                return
            }
            guard let data = document3.data() else { return }

            self.teamIDFromFirebase = data["teamID"] as? String ?? ""
            self.db.collection("diary").document(self.teamIDFromFirebase).collection("diaries").whereField("submit", isEqualTo: true).getDocuments() { (querySnapshot, err) in
                if let err = err {
                    print("Error getting documents: \(err)")
                    return self.arr = [CellData(date: parseDate(""), time: "", title: "", name: "", image:URL(string: "")!)]
                } else {
                    var i = 0
                    for document in querySnapshot!.documents {
                        self.timelineDocumentIdArr.append(document.documentID)

                        guard let documentData: [String: Any] = document.data() else { return }
                        self.dataTitleFromFireStore.append((documentData["今日のタイトル"] as? String)!)
                        self.dataTimeFromFirestore.append((documentData["time"] as? String)!)
                        self.dataNameFromFireStore.append((documentData["userName"] as? String)!)
                        self.dataImageFromFirestore.append((documentData["image"] as? String)!)
                        self.dataDateFromFiewstore.append((documentData["date"] as? String)!)

                        self.arr.append(CellData(date: parseDate(self.dataDateFromFiewstore[i] as! String), time: self.dataTimeFromFirestore[i] as? String ?? "", title: self.dataTitleFromFireStore[i] as? String ?? "", name: self.dataNameFromFireStore[i] as? String ?? "", image: URL(string: self.dataImageFromFirestore[i] as! String)!))

                        i += 1

                    }
                    self.userTable.reloadData()
                }
            }
        }
    }
    self.sections = TableSection.group(rowItems: self.arr, by: { (headline) in
        firstDayOfMonth(date: headline.date)
    })
}

func numberOfSections(in tableView: UITableView) -> Int {
  return self.sections.count
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  let section = self.sections[section]
  let date = section.sectionItem
  let dateFormatter = DateFormatter()
  dateFormatter.dateFormat = "yyyy年MM月dd日"
  return dateFormatter.string(from: date)
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  let section = self.sections[section]
  return section.rowItems.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell = userTable.dequeueReusableCell(withIdentifier: "cellName", for: indexPath) as! userTableViewCell
  let section = self.sections[indexPath.section]
  let cellDetail = section.rowItems[indexPath.row]
  cell.userTitle.text = cellDetail.title
  cell.userName.text = cellDetail.name
  cell.userTime.text = cellDetail.time
  cell.userImage.sd_setImage(with: cellDetail.image)
  return cell
}
}

1 个答案:

答案 0 :(得分:0)

您应在闭包内分配sections属性。 viewDidLoad方法已得到纠正:

override func viewDidLoad() {
    super.viewDidLoad()

    circleButton = Circle()

    if arr != nil {
        self.arr = []
       self.dataNameFromFireStore = [Any]()
        self.dataTimeFromFirestore = [Any]()
        self.dataTitleFromFireStore = [Any]()
        self.dataImageFromFirestore = [Any]()
        self.submitDocumentIdArr = [Any]()

        self.selectedNum = 1

        userTable.delegate = self
        userTable.dataSource = self

        userTable.register(UINib(nibName: "userTableViewCell", bundle: nil), forCellReuseIdentifier: "cellName")

        self.db.collection("users").document(self.fireAuthUID).addSnapshotListener { (snapshot3, error) in
            guard let document3 = snapshot3 else {
                print("erorr2 \(String(describing: error))")
                return
            }
            guard let data = document3.data() else { return }

            self.teamIDFromFirebase = data["teamID"] as? String ?? ""
            self.db.collection("diary").document(self.teamIDFromFirebase).collection("diaries").whereField("submit", isEqualTo: true).getDocuments() { (querySnapshot, err) in
                if let err = err {
                    print("Error getting documents: \(err)")
                    return self.arr = [CellData(date: parseDate(""), time: "", title: "", name: "", image:URL(string: "")!)]
                } else {
                    var i = 0
                    for document in querySnapshot!.documents {
                        self.timelineDocumentIdArr.append(document.documentID)

                        guard let documentData: [String: Any] = document.data() else { return }
                        self.dataTitleFromFireStore.append((documentData["今日のタイトル"] as? String)!)
                        self.dataTimeFromFirestore.append((documentData["time"] as? String)!)
                        self.dataNameFromFireStore.append((documentData["userName"] as? String)!)
                        self.dataImageFromFirestore.append((documentData["image"] as? String)!)
                        self.dataDateFromFiewstore.append((documentData["date"] as? String)!)

                        self.arr.append(CellData(date:     parseDate(self.dataDateFromFiewstore[i] as! String), time:     self.dataTimeFromFirestore[i] as? String ?? "", title:     self.dataTitleFromFireStore[i] as? String ?? "", name:     self.dataNameFromFireStore[i] as? String ?? "", image: URL(string:     self.dataImageFromFirestore[i] as! String)!))

                        i += 1

                    }

                    self.sections = TableSection.group(rowItems: self.arr, by: { (headline) in
    firstDayOfMonth(date: headline.date)
})
                    self.userTable.reloadData()
                }
            }
        }
    }
}