将单元格添加到集合视图。 Swift

Add cell to collection view. Swift

我通过 xib 创建了一个视图集合和一个自定义单元格。

单元格上只有一个Label

我要通过TextField输入文字,用这段文字填入数组,放入单元格。

我需要在 TextField 中的每个文本条目之后创建一个单元格。

我还没有使用过集合,不太了解它是如何工作的。

这就是我现在的全部

CollectionCell.swift:

import UIKit
class CollectionPlayersCell: UICollectionViewCell {

    @IBOutlet weak var playerCell: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
     //someCode
    }

}

ViewController.swift

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var collectionPlayersView: UICollectionView!
    @IBOutlet weak var nameTextFIeld: UITextField!
    let playerCellId = "playersCell"
    var playersNames = [String]()

    @IBAction func inputNameField(_ sender: UITextField) {

        playersNames.append(nameTextFIeld.text!)

    }
    override func viewDidLoad() {
        super.viewDidLoad()

        let nibPlayersCell = UINib(nibName: playerCellId, bundle: nil)
        colecctionPlayersView.register(nibPlayersCell, forCellWithReuseIdentifier: playerCellId)
        notificationKeyboard()

    }


extension ViewController: UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource
{
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: playerCellId, for: indexPath) as! CollectionPlayersCell
        cell.playerCell.text = playersNames[indexPath.row]
        return cell
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return playersNames.count
    }


}

错误:

2019-12-06 19:34:45.823972+0200 Games[3143:174982] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle

< /Users/macbookpro/Library/Developer/CoreSimulator/Devices/0DF2A96E-E367-41D3-BE33-4F3FADE3EFCE/data/Containers/Bundle/Application/2818E8FD-23FE-4E86-925B-EC3F58EF6BFC/Games.app > (loaded)' with name 'playersCell''

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

要让集合视图自行更新,您需要调用其 reloadData() 方法。

所以你的 IBAction 应该是这样的:

@IBAction func inputNameField(_ sender: UITextField) {
        playersNames.append(nameTextFIeld.text!)
        collectionPlayersView.reloadData()
}

您需要在您的 xib 文件中设置单元标识符 "playersCell" 并在 viewDidLoad

中设置 collectionView.delegate = selfcollectionView.dataSource = self

您需要提及您的 xib 文件名而不是 "playerCellId"

let nibPlayersCell = UINib(nibName: playerCellId, bundle: nil)

需要 nibName = "YourNibName"

如果你的nib名称是CollectionPlayersCell,那么应该是这样的-

let nibPlayersCell = UINib(nibName: "CollectionPlayersCell", bundle: nil)