CollectionViewControllerCell的问题没有显示CollectionViewController

时间:2018-03-04 17:17:22

标签: ios swift uicollectionview

我正在使用Firebase制作iPhone应用,我遇到以下代码的小问题。

import UIKit
import Firebase

class ChatController: UICollectionViewController, UITextFieldDelegate, UICollectionViewDelegateFlowLayout {
    var game: Game? {
        didSet {
            navigationItem.title = game?.name
        }
    }

    lazy var inputTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "Enter message..."
        textField.translatesAutoresizingMaskIntoConstraints = false
        return textField
    }()

    let cellId = "cellId"

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.alwaysBounceVertical = true
        collectionView?.backgroundColor = UIColor.white
        collectionView?.register(ChatMessageCell.self,  forCellWithReuseIdentifier: cellId)

        setupInputComponents()
    }

    var messages = [Message]()

    func observeMessages() {
        let ref = Database.database().reference().child("games").child((game?.id)!).child("messages")
        ref.observe(.childAdded, with: { (snapshot) in
            if let dictionary = snapshot.value as? [String: AnyObject] {
                let message = Message()
                message.setValuesForKeys(dictionary)
                self.messages.append(message)

                DispatchQueue.main.async {
                    self.collectionView?.reloadData()
                }
            }
        }, withCancel: nil)
    }

    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: cellId, for: indexPath as IndexPath) as! ChatMessageCell

//        let message = messages[indexPath.item]
//        cell.textView.text = message.text
        cell.backgroundColor = UIColor.blue

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: NSIndexPath) -> CGSize {
        return CGSize(width: view.frame.width, height: 80)
    }

    // Sets up the entire message sending
    // container for the send button and input
    // text field
        func setupInputComponents() {
        // Creates the container for send button
        // and input text field
        let containerView = UIView()
        containerView.backgroundColor = UIColor.white
        containerView.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(containerView)

        // anchor constraints and x,y,w,h
        // for positioning the container
        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

        // Creates the send button
        let sendButton = UIButton(type: .system)
        sendButton.setTitle("Send", for: .normal)
        sendButton.translatesAutoresizingMaskIntoConstraints = false
        sendButton.addTarget(self, action: #selector(handleSend), for: .touchUpInside)
        containerView.addSubview(sendButton)

        // Positions the send button within the container
        sendButton.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true
        sendButton.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
        sendButton.widthAnchor.constraint(equalToConstant: 80).isActive = true
        sendButton.heightAnchor.constraint(equalTo: containerView.heightAnchor).isActive = true

        // Creates the input text field
        containerView.addSubview(inputTextField)

        // Positions the send button within the container
        inputTextField.leftAnchor.constraint(equalTo: containerView.leftAnchor, constant: 8).isActive = true
        inputTextField.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
        inputTextField.rightAnchor.constraint(equalTo: sendButton.leftAnchor).isActive = true
        inputTextField.heightAnchor.constraint(equalTo: containerView.heightAnchor).isActive = true

        // Create a seperator for this component
        let seperatorLineView = UIView()
        seperatorLineView.backgroundColor = UIColor(r: 220, g: 220, b: 220)
        seperatorLineView.translatesAutoresizingMaskIntoConstraints = false
        containerView.addSubview(seperatorLineView)

        // Positions the seperator
        seperatorLineView.leftAnchor.constraint(equalTo: containerView.leftAnchor, constant: 8).isActive = true
        seperatorLineView.widthAnchor.constraint(equalTo: containerView.widthAnchor).isActive = true
        seperatorLineView.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
        seperatorLineView.heightAnchor.constraint(equalToConstant: 1).isActive = true
    }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }

    @objc func handleSend() {

        let ref = Database.database().reference().child("games").child("-L6lIJt_cw6saNNWMgu1").child("messages")
        ref.keepSynced(true)
        let childRef =  ref.childByAutoId()
        let values = ["text": inputTextField.text!]
        childRef.updateChildValues(values)
    }
}

我有一些注释掉的部分实际上是我想要在我的单元格中显示为文本但我甚至无法在CollectionViewController中为我显示彩色框。数据库检索代码工作得很好,我可以在TableViewController中显示它给我的内容。它不在我在这里制作的CollectionViewController中。

正是发生了什么,应用程序构建和加载成功,但当我导航到此屏幕时,我正在创建的单元格没有显示。这些行具体如下:

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return messages.count
//        return 5
}

override func collectionView(_ collectionView: UICollectionView,, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath as IndexPath) as! ChatMessageCell

//        let message = messages[indexPath.item]
//        cell.textView.text = message.text
    cell.backgroundColor = UIColor.blue

    return cell
}


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: NSIndexPath) -> CGSize {
    return CGSize(width: view.frame.width, height: 80)
}

1 个答案:

答案 0 :(得分:1)

您需要添加以下代理和数据源。

向您的班级添加UICollectionViewDataSourceUICollectionViewDelegate

然后在viewDidLoad添加self.collectionView?.delegate = selfself.collectionView?.dataSource = self

这告诉视图控制器它的委托和数据源方法在它自己的类中。 这应该可以解决您的问题。很抱歉,如果此答案中的格式有点偏差。在我的手机上,所以在输入答案时看不到问题!