我的一个ViewControllers中有以下代码。我想在tableview中显示评论。写作和阅读有效,但它们根本不会出现在我的桌面视图中。
问题在于它首先显示视图并在之后加载数据。我也不能调用tableview函数。任何帮助都会很棒!
import UIKit
import FirebaseDatabase
class SinglePostViewController: UIViewController, UITableViewDelegate,
UITableViewDataSource {
@IBOutlet weak var commentTextfield: UITextField!
var commentList:[Comment] = CommentData().loadFromDatabase(postID: "")
@IBOutlet weak var tableView: UITableView!
@IBAction func commentButton(_ sender: Any)
{
// saving comment to database
if commentTextfield.text != ""
{
let com : Comment = Comment()
com.setContent(content: commentTextfield.text!)
CommentData().saveToDatabase(comment: com)
}
}
// setting up tableview
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return commentList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
print("check tableview")
let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.textLabel?.text = commentList[indexPath.row].getContent()
return cell
}
func refresh(){
commentList = CommentData().loadFromDatabase(postID: "")
self.tableView.reloadData()
}
override func viewDidLoad() {
print("check viewdidload")
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
CommentData的代码:
import UIKit
import Firebase
import AVFoundation
class CommentData: NSObject {
var databaseReference : DatabaseReference{
return Database.database().reference()
}
var databaseHandle : DatabaseHandle = 0
func saveToDatabase(comment : Comment){
do{
self.databaseReference.child("Comment").childByAutoId().setValue(["userID": comment.getUserID(), "postID" : comment.getPostID(), "content" : comment.getContent(),"LikeFlagCounter" : comment.getLikeFlagCounter()])
}
}
func loadFromDatabase(postID : String) -> [Comment]{
var comments : [Comment] = []
databaseHandle = databaseReference.child("Comment").observe(.childAdded, with: { (snapshot) in
let comment = Comment()
if let dictionary = snapshot.value as? [String : AnyObject] {
for (key, value) in dictionary{
if key == "userID"{
comment.setUserID(userID: value as! Int)
}
else if key == "postID"{
comment.setPostID(postID: value as! String)
}
else if key == "content"{
comment.setContent(content: value as! String)
}
else if key == "LikeFlagCounter" {
comment.setLikeFlagCounter(likeFlagCounter: value as! Int)
}
}
}
print(comment.getPostID())
print(postID)
if comment.getPostID() == postID
{
comments.append(comment)
print(comments.count)
}
})
print("check!!!!!" + String(comments.count))
return comments
}
}
答案 0 :(得分:0)
您尚未为tableView设置dataSource。试试它应该工作。无需在viewDidload上调用reload
@IBOutlet weak var tableView: UITableView! {
didSet {
tableView.dataSource = self
}
}