【发布时间】:2021-08-03 10:01:58
【问题描述】:
我在代码中遇到了问题,而且我是新手,所以我边走边学(所以请宽容!)。本质上,我有一个 tableView,它在用户添加数据时显示数据。例如,用户在多天添加他的体重并显示。我发现如果我对“日志”使用结构,它只会显示一个带有一条数据的表格视图单元格。但是,当我使用“日志”类时,它会显示所有数据。一般情况是这样吗?我最初将表格视图的代码编写为“类日志”,但需要将其更改为结构,我遇到了这个问题。我希望代码易于阅读!有人可以让我知道如何改进我的代码/给我任何指示吗?谢谢!
VC
struct Log {
var title: String
var Diary: [Diary]
init(title: String, Diary: [Diary]) {
self.title = title
self.Diary = Diary
}
}
struct Diary {
var id: String?
var Weight: String
var Body: String
var date: String?
var dateFormatted: Date?
init(id: String? = nil, Weight: String, Body: String, date: String? = nil, dateFormatted: Date? = nil) {
self.id = id
self.Weight = Weight
self.Body = Body
self.date = date
self.dateFormatted = dateFormatted
}
}
@IBOutlet weak var logList: UITableView!
@IBOutlet weak var logTitle: UILabel!
var Diary = [Diary]()
var Logs: [Log] = [Log].init()
override func viewDidLoad() {
super.viewDidLoad()
self.fetchData(for: todayDate)
}
获取数据
func fetchData(for date: String) {
guard let userId = Auth.auth().currentUser?.uid else { return }
let LogRef = Database.database().reference().child("users/\(userId)/Log")
LogRef.removeAllObservers()
databaseRef = LogRef.child(date)
databaseRef.observe(.value, with: {(snapshot) in
self.Diary.removeAll()
self.Logs.removeAll()
if snapshot.childrenCount>0 {
for title in snapshot.children.allObjects as! [DataSnapshot] {
print("title = ", title)
if let logObject = title.value as? [String: AnyObject],
let title = logObject["Body"] as? String,
let Weight = logObject["Weight"] as? String {
let title = Diary(id: title.key, Body: Body, Weight: Weight)
self.Diary.append(title)
if var Log = self.Logs.first(where: {$0.title == title}) {
Log.Diary.append(title)
}else {
self.Logs.append(Log.init(title: title, Diary: [title]))
}
}else if title.key == "logTitle",
let logTitle = title.value as? String {
self.logTitle.text = logTitle
}
}
}
self.logList.reloadData()
})
}
表视图代码相关:
func numberOfSections(in tableView: UITableView) -> Int {
return self.Logs.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.Logs[section].title.uppercased()
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.hiddenSections.contains(section) {
return 0
}
return self.Logs[section].Diary.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = logList.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! LogTableViewCell
let title: Diary = self.Logs[indexPath.section].Diary[indexPath.row]
cell.body.text = title.Body
cell.weight.text = title.Weight
return cell
}
}
【问题讨论】:
-
不相关但很重要:类型名称使用大写字母,变量名称使用小写字母。返回并在您曾经编写过的所有代码中修复此问题现在,包括这个问题。
-
嗨@matt,我知道这是我的一个坏习惯,我需要改正!
标签: swift uitableview