我正在处理ios
应用程序。我有一个自定义表格单元,其中定义了我的参数。我的原型单元中还有两个标签(名称和作者)。我希望将名称和作者的字符串值从数据库中读取到数组的标签中。
但是,我一直坚持如何将firebase
中的字符串值附加到这些标签中。请帮忙。
class ViewController: UIViewController, UITableViewDelegate,
UITableViewDataSource{
var ref:DatabaseReference!
var books = [Books]()
@IBOutlet weak var mainTableView: UITableView!
override func viewWillAppear(_ animated: Bool) {
mainTableView.reloadData()
super.viewWillAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
mainTableView.rowHeight = 120
// Do any additional setup after loading the view, typically from a nib.
//Set the firebase reference
Database.database().reference()
//retrieve the posts and listen for changes
ref?.child("Books").observe(.childAdded, with: {(snapshot) in
let post = snapshot.value as? String
if let actualPost = post {
self.post.append(actualPost)
self.mainTableView.reloadData()
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return books.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let bookCell = tableView.dequeueReusableCell(withIdentifier: "BookCell", for: indexPath) as! CustomTableViewCell
let idx:Int = indexPath.row
bookCell.bookName?.text = books[idx].name
bookCell.bookAuthor?.text = books[idx].author
return bookCell
}
答案 0 :(得分:0)
一种简洁的方法是为您的类型定义一个Class
。我们了解到,您正在介绍的是作者写的书和作者的名字:
Class Book {
var booksWritten:[Array]?
var authorsName:String?
init(booksFromFB:[Array], nameFromFB:String) {
self.booksWritten = booksFromFB
self.authorsName = nameFromFB
}
}
在调用Firebase的ViewController中,您声明一个变量,该变量是Book
s的数组。
var books = [Books]()
从Firebase取回快照时,请使用该记录的属性初始化Book类型的变量:
var ref: DatabaseReference!
ref = Database.database().reference()
ref?.child("Books").observe(DataEventType.value, with: { (snapshot) in
guard let snapshot = snapshot.children.allObjects as? [DataSnapshot] else { return }
for book in snapshot {
let books = book.childSnapshot(forPath: "Books").value as? [String]
let author = book.childSnapshot(forPath: "Author").value as? String
let book = Book(booksFromFB: books, authorFromFB: author)
books.append(book)
}
self.mainTableView.reloadData()
}) { (error) in
print(error.localizedDescription)
}
为您的单元格创建一个类。 (不要忘记在情节提要中设置其标识符)
class BooksTableViewCell: UITableViewCell {
@IBOutlet weak var books: UILabel!
@IBOutlet weak var author: UILabel!
func configureCell(books:Array, author:String){
self.books.flatMap({$0}).joined() = books
self.author.text=author
}
}
最后一步:
func tableView(_ tableView:UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = mainTableView.dequeueReusableCell(withIdentifier: "BooksTableViewCell") as? BooksTableViewCell else { return UITableViewCell() }
let book = books[indexPath.row]
cell.configureCell(books: book.booksWritten, author: book.authorsName)
return cell
}
PS:当您不再需要任何观察者时,请不要忘记删除它们。