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

问题描述 投票:0回答:1

我通过xib创建了视图集合和自定义单元格。单元格上只有一个标签。我必须通过文本字段输入文本,用此文本填充数组并将其放在单元格中。

所以我需要在文本字段中的每个文本输入之后创建一个单元格。我还没有使用过收藏,还不太了解它是如何工作的。

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
    }


}

我通过xib创建了视图集合和自定义单元格。单元格上只有一个标签。我必须通过文本字段输入文本,用此文本填充数组并将其放在单元格中。 ...

ios swift cell add collectionview
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.