【发布时间】:2018-04-07 14:17:48
【问题描述】:
我的一个 ViewController 中有以下代码。我正在尝试在表格视图中显示 cmets。写作和阅读有效,但它们根本不会出现在我的表格视图中。
问题在于它先显示视图,然后再加载数据。我也不能调用 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
}
}
【问题讨论】:
-
因为在您的视图中加载
commentList为空,一旦获取结果,您需要调用reloadData或从您的viewDidLoad()调用refresh()
标签: ios arrays swift uitableview reload