简体   繁体   中英

UITableView not loading

I social app like Facebook and I'm trying to add a comment section into every post, so far I added a UITableView and it is actually downloading all the comments but when it runs they don't appear, here goes my code.

Table View Controller

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()
    }

this part actually works and it loads perfectly all the comments into the self.comments var

this is my configuration.

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

}

and lastly this is my CommentTableViewCell code

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
    }


}

The whole ViewController Code

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)
    }
}

Did init your self.comments array like

var comments: [Post] = []

or you Did you try reloadData() in MainThread. Like

DispatchQueue.main.async(execute: {
    self.commentTable.reloadData()
})

Just solve it, as mention by @DonMag I had missing this lines of code:

self.commentTable.delegate = self
self.commentTable.dataSource = self

they problem was my functions numberOfSections, numberOfRowsInSection etc weren't been called because because I didn't set the delegate and data source at the beginning.

so for future reference for every tableView and CollectionView you have you need to put this in the ViewDidLoad()

self.<Your_TableOrCollectionView>.delegte = self
self.<Your_TableOrCollectionView>.dataSource = self

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM