UILabel文本编辑后的UITableViewCell重复

时间:2018-04-05 09:39:04

标签: ios swift uitableview firebase uilabel

我有UITabelViewCell用于显示与联系人的有效聊天。

有一个标签显示每个联系人的未读邮件数量,信息来自Firebase。

打开聊天时,显示未读邮件数量的UILabel应该会消失。但是,一旦它完成,它就会创建另一个单元格,如下图所示:

Before opening chat

然后我点击聊天,打开聊天,然后点击"返回"导航项目,显示:

After navigating back to TableView

这是我的班级:

import UIKit
import Firebase

class MessagesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate
{

    private var chats = [PrivateChatLiteObject]()

    @IBOutlet weak var ChatsTableView: UITableView!
    override func viewDidLoad()
    {
        super.viewDidLoad()

        ChatsTableView.dataSource = self
        ChatsTableView.delegate = self
        self.view.layer.backgroundColor = UIColor.white.cgColor
        populateActiveChats()
    }

    private func populateActiveChats()
    {
        let loggedOnUserID = Auth.auth().currentUser?.uid
        let ref = Constants.refs.databaseChatsLite.child(loggedOnUserID!)

            // Retrieve the products and listen for changes
        ref.observe(.value, with:
                { (snapshot) in

                    for child in snapshot.children.allObjects as! [DataSnapshot]
                    {
                        // Code to execute when new product is added

                        let chatValueDictionary = child.value as? NSDictionary
                        self.AddChatToCollections(chatAsDictionary: chatValueDictionary, contactID: child.key)
                        self.DispatchQueueFunc()

                    }
            })
    }

    func AddChatToCollections(chatAsDictionary: NSDictionary!, contactID: String)
    {
        let contactName = chatAsDictionary["userName"] as! String
        //let contactImg = chatAsDictionary["userImageStr"] as? String
        //let lastMsg = chatAsDictionary["lastMessage"] as! String
        let newMsgs = chatAsDictionary["newMessage"] as! Int


        let chatToAdd = PrivateChatLiteObject(chattingWith: contactName, ContactID: contactID, unreadMessages: newMsgs, LastMSG: "")

        chats.append(chatToAdd)
    }

    func DispatchQueueFunc()
    {
        DispatchQueue.main.async
            {
                self.ChatsTableView.reloadData()
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return chats.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = ChatsTableView.dequeueReusableCell(withIdentifier: "chat_room_cell", for: indexPath) as! PrivateChatUITableViewCell

        //cell.ContactImageView = UIImageView.loadImageUsingUrlString(contactImg)
        let index = indexPath.row
        cell.ContactName.text = chats[index].GetContactName()

        cell.ContactID = chats[index].GetContactID()

        let unreadMSGs = chats[index].GetUnreadMessagesNumber()

        if unreadMSGs == 0
        {
            cell.NewNotificationsNum.isHidden = true
        }
        else
        {
            cell.NewNotificationsNum.isHidden = false
            let stringNotifications = String(unreadMSGs)
            cell.NewNotificationsNum.text = stringNotifications
        }

        return cell

    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {

        chatIndexToLoad = indexPath.row
        performSegue(withIdentifier: "segue_to_chatroom", sender: self)
    }

    var chatIndexToLoad: Int = -1

    override func prepare(for segue: UIStoryboardSegue, sender: Any?)
    {
        if (segue.identifier == "segue_to_chatroom")
        {
            let destination = segue.destination as! PrivateChatViewController
            destination.senderId = Constants.refs.currentUserInformation!.uid
            //destination.senderDisplayName = Constants.refs.currentUserInformation?.displayName
            destination.contactDisplayName = chats[chatIndexToLoad].GetContactName()
            destination.contactID = chats[chatIndexToLoad].GetContactID()

        }
    }

}

我想当必须在节点内部进行更改并重新添加同一节点时,必须执行从Firebase读取操作的操作。我需要一种方法,只有在添加新节点时才能从Firebase启动读取。我尝试使用.childAdded,但这并没有奏效。有谁知道如何解决这个问题?

我唯一可以想到的是,只要在收集中添加项目,检查具有相同联系人ID的聊天是否还不存在,但这对性能不利。

2 个答案:

答案 0 :(得分:0)

我并不完全知道你要求的是什么,但是如果你愿意,我可以分享我现有的代码,如下所示。此外,请确保将UITableView作为委托和数据源附加到ViewController,并将其添加到视图控制器类中:

class NearbyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var nearbyTableView: UITableView!
var myList: [String] = []
var handle:DatabaseHandle?
var ref:DatabaseReference?






func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return myList.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
    var (cellName) = myList[indexPath.row]
    cell.textLabel?.text = cellName

    return cell

}

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
    var (cellName) = myList[indexPath.row]

    print("row\(indexPath.row)")
    print("name: \(cellName)")


}


override func viewDidLoad() {
    super.viewDidLoad()






    ref = Database.database().reference()
    handle = ref?.child("list").observe(.childAdded, with: { (snapshot) in
        if let item = snapshot.value as? String
        {
            self.myList.append(item)
            self.nearbyTableView.reloadData()
        }
    })
}
}

答案 1 :(得分:0)

当您在FirebaseDatabase中查询某些数据而不是使用

ref.observe(.value, with: { (snapshot) in

             //your implementation
    })

尝试使用

ref.observeSingleEvent(of: .value, with: { (snapshot) in

             //your implementation
})

当我在其中一个项目中使用它时,我注意到FirebaseDatabase的这种奇怪行为。多次调用ref.observe并导致意外结果,而ref.observeSingleEvent完成了其工作。