【发布时间】:2020-09-28 11:27:29
【问题描述】:
我正在使用 Swift 和 Firestore,我在其中收集任务。
我用任务数据填充每个 tableview 单元格。有一个字段标签。现在它只是一个字符串,但我希望它是一个字符串数组。
如何在任务模型中保存字符串数组并在表格视图中正确显示?
我的任务模型文件:
import Foundation
import FirebaseFirestore
protocol DocumentSerializable {
init?(dictionary:[String:Any])
}
struct Task {
var title: String
var description: String
var tip: String
var hashtags: String
var dictionary:[String:Any] {
return [
"title": title,
"description": description,
"tip": tip,
"hashtags": hashtags
]
}
}
extension Task : DocumentSerializable {
init?(dictionary: [String : Any]) {
let title = dictionary["title"] as? String ?? "Error! Title Field Not Found!"
let description = dictionary["description"] as? String ?? "Error! Description Field Not Found!"
let tip = dictionary["tip"] as? String ?? "Error! Tip Field Not Found!"
let hashtags = dictionary["hashtags"] as? String ?? "Error! Hashtags Field Not Found!"
self.init(title: title, description: description, tip: tip, hashtags: hashtags)
}
}
我的 TableViewViewController 文件:
import UIKit
import Firebase
import FirebaseAuth
import FirebaseFirestore
class TasksListScreen: UIViewController {
var db = Firestore.firestore()
var tasksArray = [Task]()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
loadData()
}
// load data from the user tasks collection to the table view
func loadData() {
let userID = Auth.auth().currentUser!.uid
let userTasksCollRef = db.collection("users").document(userID).collection("tasks")
userTasksCollRef.getDocuments { (queryShapshot, error) in
if let error = error {
print("Error loading data: \(error.localizedDescription)")
} else {
self.tasksArray = queryShapshot!.documents.compactMap({Task(dictionary: $0.data())})
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
}
extension TasksListScreen: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tasksArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "taskCell") as! TaskViewCell
let task = tasksArray[indexPath.row]
cell.previewTitleLabel.text = task.title
cell.previewMotivLabel.text = task.description
cell.previewTipLabel.text = task.tip
cell.previewHashtagsLabel.text = task.hashtags
cell.cellDelegate = self
cell.index = indexPath
return cell
}
}
【问题讨论】:
-
您遇到了什么问题?
-
您好!我不知道如何在我的任务模型中正确地将主题标签字段存储为数组而不是字符串。
标签: ios arrays swift firebase google-cloud-firestore