我正在尝试创建一个消息应用程序。当我尝试显示单元格时,将消息包含在UICollectionView
它们没有显示。 我首先要为单元格提供红色背景并显示模型中的项目。我在消息数组中。谁能告诉我为什么他们没有人口?
import UIKit
import Firebase
class ChatLogController: UICollectionViewController,
UITextFieldDelegate, UICollectionViewDelegateFlowLayout{
var messages = [Message]()
var user: User?{
didSet{
navigationItem.title = user?.name
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(handleBackBtnPressed))
observeMessages()
}
}
lazy var inputTextField: UITextField = {
let textField = UITextField()
textField.placeholder = "Enter Message..."
textField.translatesAutoresizingMaskIntoConstraints = false
textField.delegate = self
return textField
}()
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.backgroundColor = UIColor.white
collectionView?.register(ChatMessageCell.self, forCellWithReuseIdentifier: "cell")
collectionView?.delegate = self
collectionView?.dataSource = self
setupInputComponents()
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return messages.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ChatMessageCell
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
//set the size
return CGSize(width: self.view.frame.width, height: 80)
}
func setupInputComponents(){
let containerView = UIView()
containerView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(containerView)
//constraints
containerView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
containerView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
containerView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
containerView.heightAnchor.constraint(equalToConstant: 50).isActive = true
containerView.backgroundColor = UIColor.white
let sendBtn = UIButton(type: .system)
sendBtn.setTitle("Send", for: .normal)
sendBtn.translatesAutoresizingMaskIntoConstraints = false
sendBtn.addTarget(self, action: #selector(handleSend), for: .touchUpInside)
containerView.addSubview(sendBtn)
sendBtn.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true
sendBtn.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
sendBtn.widthAnchor.constraint(equalToConstant: 80).isActive = true
sendBtn.heightAnchor.constraint(equalTo: containerView.heightAnchor).isActive = true
containerView.addSubview(inputTextField)
inputTextField.leftAnchor.constraint(equalTo: containerView.leftAnchor, constant: 8).isActive = true
inputTextField.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
inputTextField.rightAnchor.constraint(equalTo: sendBtn.leftAnchor).isActive = true
inputTextField.heightAnchor.constraint(equalTo: containerView.heightAnchor).isActive = true
let separator = UIView()
separator.backgroundColor = UIColor.lightGray
separator.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(separator)
separator.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true
separator.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
separator.widthAnchor.constraint(equalTo:containerView.widthAnchor).isActive = true
separator.heightAnchor.constraint(equalToConstant: 1).isActive = true
}
func handleSend(){
let reference = FIRDatabase.database().reference().child("messages")
let childRef = reference.childByAutoId()
let toId = user!.id!
let fromId = FIRAuth.auth()!.currentUser!.uid
let timeStamp = Date().timeIntervalSince1970
let values = ["text":inputTextField.text!,"toId":toId,"fromId":fromId,"timeStamp":timeStamp] as [String : AnyObject]
childRef.updateChildValues(values) { (error, ref) in
if error != nil{
print(error?.localizedDescription ?? "")
return
}
let userMessagesRef = FIRDatabase.database().reference().child("user-messages").child(fromId)
let messageId = childRef.key
userMessagesRef.updateChildValues([messageId:1])
let recipientUserMessageRef = FIRDatabase.database().reference().child("user-messages").child(toId)
recipientUserMessageRef.updateChildValues([messageId:1])
}
}
func handleBackBtnPressed(){
let messageController = MessagesVC()
let navController = UINavigationController(rootViewController: messageController)
self.present(navController, animated: true, completion: nil)
}
func observeMessages(){
guard let uid = FIRAuth.auth()?.currentUser?.uid else{
return
}
let ref = FIRDatabase.database().reference().child("user-messages").child(uid)
ref.observe(.childAdded, with: { (snapshot) in
let messageId = snapshot.key
let messagesRef = FIRDatabase.database().reference().child("messages").child(messageId)
messagesRef.observeSingleEvent(of: .value, with: { (snapshot) in
guard let dictionary = snapshot.value as? [String:AnyObject] else{
return
}
let message = Message()
message.setValuesForKeys(dictionary)
self.messages.append(message)
DispatchQueue.main.async {
self.collectionView?.reloadData()
}
})
})
}
}
这是聊天消息单元格
import UIKit
class ChatMessageCell: UICollectionViewCell {
let textView: UITextView = {
let tv = UITextView()
tv.text = "my text"
tv.font = UIFont.systemFont(ofSize: 16)
return tv
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.red
}
}
从 Firebase 数据库获取后,尝试检查您的消息数组是否不为空.. 将断点放在observeMessages func
中。如果您的数组不为空,并且您成功地从 firebase 数据库中获取了数据,那么您在设置 collectionView 时遇到了问题。