簡體   English   中英

UITableView未加載

[英]UITableView not loading

我是社交應用程序,例如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)
    }
}

初始化了self.comments數組像

var comments: [Post] = []

或者您在MainThread中嘗試過reloadData()嗎? 喜歡

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

只需解決它,就像@DonMag提到的那樣,我就缺少以下代碼行:

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

他們的問題是沒有調用我的函數numberOfSections,numberOfRowsInSection等,因為因為我一開始沒有設置委托和數據源。

因此,為了將來為每個tableView和CollectionView提供參考,您需要將其放入ViewDidLoad()

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM