我真的是使用swift(和一般的编码)进行IOS开发的新手,我想知道如何使用从Firestore文档中检索的数据填充表格单元格。
我正在开发的应用程序是一个个人练习项目,它是一个基本的新闻应用程序,可从消防站集合中加载文档。我试图从中加载信息的集合称为“新闻”
首先,这里是我到目前为止已完成的工作:
//So first I have a struct
struct Jobs {
var title:String
var description:String
}
class JobsTableViewController: UITableViewController {
var db:Firestore!
var jobs: Jobs?
var numOfCells = 0
override func viewDidLoad() {
super.viewDidLoad()
db = Firestore.firestore()
loadData()
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
func loadData(){
db.collection("news").getDocuments { (querySnapshot, error) in
if let error = error
{
print("\(error.localizedDescription)")
}
else
{
for document in (querySnapshot?.documents)!
{
if let Title = document.data()["title"] as? String
{
print(Title) //I have this here to see if the new was being retrieved and it was.
self.title = Title
self.numOfCells += 1
}
}
DispatchQueue.main.async
{
self.tableView.reloadData()
}
}
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numOfCells
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = title
return cell
}
So when I run the simulator this is my main screen
“新闻”集合中有3个文档,当我单击它并加载它时,这三个文档应显示在“作业”选项卡中(我在“作业”标签中显示了新闻,因为我首先想了解自己是否具备以下能力:检索数据,再加上我担心会弄乱News上已有的代码)。
当我切换到Jobs标签(这是包含我们数据的tableview所在的位置)时,I get something like this
如果您注意到我的标签栏的名称也从Jobs更改为检索到的文档标题。
In my console it shows all 3 documents have been retrieved
所以我的问题是:
1)如何将所有文档检索到表格视图的单个单元格中?
2)如何使标签栏的文本(如上所示)不更改为文档标题?
3)我的代码到底有什么问题,为什么会出错并且正在做什么呢?
4)我可以对代码进行哪些改进,为什么有必要? (就像我说的,我只是在学习所有这些内容)。
奖励问题:
5)当单击一个单元格时,如何在弹出窗口中同时显示标题和描述。
谢谢。
最佳答案
在全球范围内创造工作机会
var jobsArray = [Jobs]()
将数据库中的数组填充到您的加载数据中
for document in (querySnapshot?.documents)! {
if let Title = document.data()["title"] as? String {
print(Title)
//self.title = Title
let job = Jobs()
job.title = Title
jobsArray.append(job)
//self.numOfCells += 1
}
}
使用数组填充tableview
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return jobsArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let job = jobsArray[inedexPath.row]
cell.textLabel?.text = job.title
return cell
}