将单元格添加到集合视图。斯威夫特

我通过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] ***由于未捕获的异常'NSInternalInconsistencyException'终止了应用程序,原因:'无法在捆绑包中加载NIB:'NSBundle

     

/macbookpro/library/Developer/CoreSimulator/Devices/0DF2A96E-E367-41D3-BE33-4F3FADE3EFCE/data/Containers/Bundle/Application/2818E8FD-23FE-4E86-925B-EC3F58EF6BFC/Games.app>已加载)”,名称为“ playersCell”

     

libc ++ abi.dylib:以类型为NSException的未捕获异常终止   (lldb)

Sweetystar 回答:将单元格添加到集合视图。斯威夫特

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

所以您的IBAction应该如下所示:

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

您需要在xib文件中设置单元格标识符“ playersCell” 并在collectionView.delegate = self中设置collectionView.dataSource = selfviewDidLoad

,

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

There was a temporary DNS error. Try refreshing the page.
Error Code: INET_E_RESOURCE_NOT_FOUND

它要求nibName =“ YourNibName”

如果您的笔尖名称为CollectionPlayersCell,则应该像这样-

let nibPlayersCell = UINib(nibName: playerCellId,bundle: nil)
本文链接:https://www.f2er.com/2961256.html

大家都在问