【问题标题】:UITableView not loadingUITableView 没有加载
【发布时间】:2017-03-07 18:11:29
【问题描述】:

我像 Facebook 这样的社交应用程序,我正在尝试在每个帖子中添加评论部分,到目前为止,我添加了一个 UITableView,它实际上正在下载所有 cmets,但是当它运行时它们没有出现,这是我的代码.

表格视图控制器

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

这部分确实有效,它完美地将所有 cmets 加载到 self.cmets 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)
    }
}

【问题讨论】:

  • 在主线程上重新加载表 -: DispatchQueue.main.async{ self.tableView.reloadData() }

标签: ios firebase swift3 firebase-realtime-database


【解决方案1】:

是否像这样初始化了 self.cmets 数组

var comments: [Post] = []

或者你有没有在 MainThread 中尝试过 reloadData()。喜欢

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

【讨论】:

  • 我刚刚添加了 var cmets: [Post] = [] 它也不起作用,我应该把 DispatchQueue.main.async(execute: { self.commentTable.reloadData() } ) ???
  • 就在您获得所有数据重新加载表之后,因为所有与 ui 相关的部分都在主线程上完成。
  • 你能把所有的代码都贴在你的 ViewController 里吗?
  • 完成 ;)。查看原帖
  • 您是否将 Delegate 和 DataSource 连接到 Storybord 中的 ViewController 中?喜欢self.commentTable.delegate = self``self.commentTable.dataSource = self
【解决方案2】:

只要解决它,正如@DonMag 提到的,我错过了这行代码:

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

他们的问题是我的函数 numberOfSections、numberOfRowsInSection 等没有被调用,因为我一开始没有设置委托和数据源。

所以为了将来对每个 tableView 和 CollectionView 的参考,你需要把它放在 ViewDidLoad() 中

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

【讨论】:

    猜你喜欢
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多