我像Facebook这样的社交应用程序,我试图在每个帖子中添加评论部分,到目前为止我添加了一个UITableView,它实际上是在下载所有评论但是当它运行时它们不会出现,这是我的代码。
表视图控制器
func fetchPosts() //it runs in the viewDidLoad
{
print("LoggedInUser: " + (self.loggedInUser?.uid)!)
FIRDatabase.database().reference().child("Jalas").child((self.post?.UserID)!).child((self.post?.PostID)!).child("Comments").observe(.childAdded, with: { (snapshot:FIRDataSnapshot) in
let postsSnap = snapshot.value as? [String : AnyObject]
if(postsSnap != nil)
{
print(postsSnap!)
let posst = Post()
let author = postsSnap?["name"] as? String
let userID = postsSnap?["userID"] as? String
let pathToImage = postsSnap?["pp"] as? String
let HD = postsSnap?["handle"] as? String
//let lik = postsSnap?["Jalos"] as? Int
let text = postsSnap?["text"] as? String
//let postID = postsSnap?["postID"] as? String
posst.Author = author
posst.PathToImage = pathToImage
//posst.PostID = postID
posst.UserID = userID
posst.Handle = HD
//posst.Jalos = lik
posst.Post = text
self.comments.append(posst)
self.commentTable.reloadData()
}
})
FIRDatabase.database().reference().removeAllObservers()
}
这部分确实有效,它将所有注释完全加载到self.comments var
中这是我的配置。
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.comments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: CommentTableViewCell = tableView.dequeueReusableCell(withIdentifier: "Comment", for: indexPath) as! CommentTableViewCell
cell.comment.text = self.comments[indexPath.row].Post
cell.handle.text = ("@" + self.comments[indexPath.row].Handle)
cell.name.text = self.comments[indexPath.row].Author
cell.pp.downloadImage(from: self.comments[indexPath.row].PathToImage)
return cell
}
最后这是我的CommentTableViewCell代码
class CommentTableViewCell: UITableViewCell {
@IBOutlet weak var name: UILabel!
@IBOutlet weak var handle: UILabel!
@IBOutlet weak var pp: UIImageView!
@IBOutlet weak var comment: UITextView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
整个ViewController代码
import UIKit
import Firebase
import FirebaseDatabase
import FirebaseAuth
class PostViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {
var post : Post?
let databaseRef = FIRDatabase.database().reference()
let loggedInUser = FIRAuth.auth()?.currentUser
var active = false
let textView = GrowingTextView()
@IBOutlet weak var scroll: UIScrollView!
@IBOutlet weak var Jalo: UIButton!
@IBOutlet weak var NoJalo: UIButton!
@IBOutlet weak var text: UITextView!
@IBOutlet weak var name: UILabel!
@IBOutlet weak var ubi: UILabel!
@IBOutlet weak var pp: UIImageView!
@IBOutlet weak var handle: UILabel!
@IBOutlet var mainView: UIView!
@IBOutlet weak var bottomConstraint: NSLayoutConstraint!
@IBOutlet var toolBar: UIToolbar!
@IBOutlet weak var commentTable: UITableView!
var comments: [Post] = []
override func viewDidLoad() {
super.viewDidLoad()
self.mainView.backgroundColor = UIColor.black
self.scroll.backgroundColor = UIColor.white.withAlphaComponent(0.85)
self.post = Posts.sharedInstance.po
FIRDatabase.database().reference().child("Jalas").child((self.post?.UserID)!).child((self.post?.PostID)!).child("users").queryOrderedByValue().queryEqual(toValue: true).observeSingleEvent(of: .value, with: {(snap) in
let sanpDict = snap.value as? [String : AnyObject]
if(sanpDict != nil)
{
for each in sanpDict!{
if (each.key == self.loggedInUser?.uid)
{
self.Jalo.isHidden = true
self.NoJalo.isHidden = false
}
}
}
})
self.text.text = self.post?.Post
self.name.text = self.post?.Author
self.ubi.text = self.post?.UbicacionN
self.pp.downloadImage(from: self.post?.PathToImage)
self.handle.text = self.post?.Handle
self.fetchPosts()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
self.textView.placeHolder = "Comentar..."
self.textView.placeHolderColor = UIColor(white: 0.8, alpha: 1.0)
self.textView.maxHeight = 70.0
self.textView.backgroundColor = UIColor.white
self.textView.layer.cornerRadius = 4.0
self.toolBar.addSubview(self.textView)
self.textView.translatesAutoresizingMaskIntoConstraints = false
self.toolBar.translatesAutoresizingMaskIntoConstraints = false
let views = ["textView": textView]
let hConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[textView]-65-|", options: [], metrics: nil, views: views)
let vConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-10-[textView]-10-|", options: [], metrics: nil, views: views)
toolBar.addConstraints(hConstraints)
toolBar.addConstraints(vConstraints)
self.view.layoutIfNeeded()
// constrain(inputToolbar, textView) { inputToolbar, textView in
// textView.edges == inset(inputToolbar.edges, 8, 8, 8, 8)
// }
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapGestureHandler))
view.addGestureRecognizer(tapGesture)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func keyboardWillChangeFrame(_ notification: Notification) {
self.active = true
let endFrame = ((notification as NSNotification).userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
self.bottomConstraint.constant = (view.bounds.height - endFrame.origin.y)
self.bottomConstraint.constant -= 50
self.view.layoutIfNeeded()
}
func tapGestureHandler() {
toolBar.endEditing(true)
if (self.active == true)
{
self.bottomConstraint.constant += 50
self.active = false
}
}
@IBAction func enviar(_ sender: Any) {
let text = self.textView.text
let key = self.databaseRef.child("Jalas").child(self.post!.UserID).child(self.post!.PostID).child("Comments").childByAutoId().key
//Value setting
self.databaseRef.child("Jalas").child(self.post!.UserID).child(self.post!.PostID).child("Comments").child(key).child("text").setValue(text)
self.databaseRef.child("Jalas").child(self.post!.UserID).child(self.post!.PostID).child("Comments").child(key).child("name").setValue(self.post!.Author)
self.databaseRef.child("Jalas").child(self.post!.UserID).child(self.post!.PostID).child("Comments").child(key).child("userID").setValue(self.post!.UserID)
self.databaseRef.child("Jalas").child(self.post!.UserID).child(self.post!.PostID).child("Comments").child(key).child("pp").setValue(self.post!.PathToImage)
self.databaseRef.child("Jalas").child(self.post!.UserID).child(self.post!.PostID).child("Comments").child(key).child("handle").setValue(self.post!.Handle)
self.databaseRef.child("Jalas").child(self.post!.UserID).child(self.post!.PostID).child("Comments").child(key).child("postID").setValue(self.post!.PostID)
self.databaseRef.child("Jalas").child(self.post!.UserID).child(self.post!.PostID).child("Comments").child(key).child("key").setValue(key)
//___________________________________________________________
self.tapGestureHandler()
self.textView.text = nil
}
func fetchPosts()
{
print("LoggedInUser: " + (self.loggedInUser?.uid)!)
FIRDatabase.database().reference().child("Jalas").child((self.post?.UserID)!).child((self.post?.PostID)!).child("Comments").observe(.childAdded, with: { (snapshot:FIRDataSnapshot) in
let postsSnap = snapshot.value as? [String : AnyObject]
if(postsSnap != nil)
{
print(postsSnap!)
let posst = Post()
let author = postsSnap?["name"] as? String
let userID = postsSnap?["userID"] as? String
let pathToImage = postsSnap?["pp"] as? String
let HD = postsSnap?["handle"] as? String
//let lik = postsSnap?["Jalos"] as? Int
let text = postsSnap?["text"] as? String
//let postID = postsSnap?["postID"] as? String
posst.Author = author
posst.PathToImage = pathToImage
//posst.PostID = postID
posst.UserID = userID
posst.Handle = HD
//posst.Jalos = lik
posst.Post = text
self.comments.append(posst)
DispatchQueue.main.async(execute: {
self.commentTable.reloadData()
})
}
})
FIRDatabase.database().reference().removeAllObservers()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
//Dispose of any resources that can be recreated.
}
@IBAction func NoJalo(_ sender: Any) {
FIRDatabase.database().reference().child("Jalas").child((self.post?.UserID)!).child((self.post?.PostID)!).observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let like = value?["Jalos"] as! Int
var Jalos = like
Jalos = Jalos - 1
self.databaseRef.child("Jalas").child((self.post?.UserID)!).child((self.post?.PostID)!).child("Jalos").setValue(Jalos)
}) { (error) in
print(error.localizedDescription)
}
self.databaseRef.child("user_profiles").child((self.loggedInUser?.uid)!).child("JalosAsistidos").child((self.post?.PostID)!).setValue(true)
self.databaseRef.child("Jalas").child((self.post?.UserID)!).child((self.post?.PostID)!).child("users").child((self.loggedInUser?.uid)!).setValue(true)
self.NoJalo.isHidden = true
self.Jalo.isHidden = false
}
@IBAction func Jalo(_ sender: Any) {
FIRDatabase.database().reference().child("Jalas").child((self.post?.UserID)!).child((self.post?.PostID)!).observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let like = value?["Jalos"] as! Int
var Jalos = like
Jalos = Jalos + 1
self.databaseRef.child("Jalas").child((self.post?.UserID)!).child((self.post?.PostID)!).child("Jalos").setValue(Jalos)
}) { (error) in
print(error.localizedDescription)
}
self.databaseRef.child("user_profiles").child((self.loggedInUser?.uid)!).child("JalosAsistidos").child((self.post?.PostID)!).setValue(true)
self.databaseRef.child("Jalas").child((self.post?.UserID)!).child((self.post?.PostID)!).child("users").child((self.loggedInUser?.uid)!).setValue(true)
self.NoJalo.isHidden = false
self.Jalo.isHidden = true
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.comments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: CommentTableViewCell = tableView.dequeueReusableCell(withIdentifier: "Comment", for: indexPath) as! CommentTableViewCell
cell.comment.text = self.comments[indexPath.row].Post
cell.handle.text = ("@" + self.comments[indexPath.row].Handle)
cell.name.text = self.comments[indexPath.row].Author
cell.pp.downloadImage(from: self.comments[indexPath.row].PathToImage)
//cell.configure(self.comments[indexPath.row].PathToImage, name: self.comments[indexPath.row].Author, handle: self.comments[indexPath.row].Handle, text: self.comments[indexPath.row].Post)
return cell
}
}
extension PostViewController: GrowingTextViewDelegate {
func textViewDidChangeHeight(_ height: CGFloat) {
UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: [.curveLinear], animations: { () -> Void in
self.toolBar.layoutIfNeeded()
}, completion: nil)
}
}
答案 0 :(得分:0)
初始化你的self.comments数组如
var comments: [Post] = []
或者您是否在MainThread中尝试了reloadData()。像
DispatchQueue.main.async(execute: {
self.commentTable.reloadData()
})
答案 1 :(得分:0)
刚刚解决它,正如@DonMag所提到的那样,我错过了这行代码:
self.<Your_TableOrCollectionView>.delegte = self
self.<Your_TableOrCollectionView>.dataSource = self
他们的问题是我的函数numberOfSections,numberOfRowsInSection等没有被调用,因为我没有在开头设置委托和数据源。
因此,对于每个tableView和CollectionView的未来参考,您需要将它放在ViewDidLoad()
中{{1}}