Пользовательское содержимое ячейки в UICollectionView

Я пытаюсь добавить UICollectionView в быстрый класс программно, без раскадровки, с настраиваемой ячейкой (простой ярлык в каждой ячейке)

import Foundation
import UIKit

class BoardView : UIView, UICollectionViewDataSource, UICollectionViewDelegate {

    var boardTable: UICollectionView!
    var cellLabel:UILabel!
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()

    var items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

    convenience init(frame: CGRect, title: String) {
        self.init(frame: frame)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        layout.sectionInset = UIEdgeInsets(top: 60, left: 10, bottom: 10, right: 10)
        layout.itemSize = CGSize(width: 30, height: 30)
        boardTable = UICollectionView(frame: self.frame, collectionViewLayout: layout)
        boardTable.dataSource = self
        boardTable.delegate = self
        boardTable.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        boardTable.backgroundColor = UIColor.clear
        self.addSubview(boardTable)

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("MainViewis not NSCoding compliant")
    }

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath)
        cellLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
        cellLabel.textAlignment = .center
        cellLabel.text = self.items[indexPath.item]
        cell.contentView.addSubview(cellLabel)
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
    {
        print("User tapped on item \(indexPath.row)")
    }    
}

Я могу изменить фон ячейки с помощью кода

let cell = self.boardTable.cellForItem(at: IndexPath(row: 1 , section: 0))
cell?.backgroundColor = UIColor.lightGray

Как я могу изменить цвет текста ячейки или текстовое содержимое ячейки (cellLabel)?

Заранее спасибо за вашу поддержку.

4 ответа

Решение

Есть два способа сделать это

1) Создайте пользовательский класс UICollectionviewcell, в котором в качестве свойства будет указан cellLabel.

Создайте класс coustom, скажем, CollectionViewCell

Класс CollectionViewCell: UICollectionViewCell {var cellLabel: UILabel!

    override func drawRect(rect: CGRect) { //Your code should go here.
        super.drawRect(rect)

    }

}

И чтобы создать ячейку custon, измените следующую функцию

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

        cellLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
        cellLabel.textAlignment = .center
        cellLabel.text = self.items[indexPath.item]
        cell.contentView.addSubview(cellLabel)
        return cell
    }

Для изменения свойства cellLabel используйте код ниже

let cell = self.boardTable.cellForItem(at: IndexPath(row: 1 , section: 0))  as! CollectionViewCell
cell?.backgroundColor = UIColor.lightGray
cellLabel.textColor = .white
cellLabel.textColor = UIColor(red: 100.0, green: 100.0, blue: 100.0, alpha: 1) 
cellLabel.text = "Hello World"

2) Итерируйте по подвиду ячейки и найдите метку по классу UILabel, а затем измените ее свойство.

for view in cell.subviews {
    if let label = view as? UILabel {
        label.textColor = UIColor.red
     }
 }

Я бы предложил использовать 1-й.

Попробуй это:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath)
        var colors : [UIColor] = [UIColor.blue , UIColor.red , UIColor.cyan]
        cellLabel.textColor = colors[indexPath.row]

        cellLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
        cellLabel.textAlignment = .center
        cellLabel.text = self.items[indexPath.item]
        cell.contentView.addSubview(cellLabel)
        return cell
    }
/* For text color */

//Default set of colours
cellLabel.textColor = .white


//Color of your choice - RGB components in as float values
cellLabel.textColor = UIColor(red: 100.0, green: 100.0, blue: 100.0, alpha: 1) 

/* For text content */
cellLabel.text = "Hello World"

Пока вы можете использовать это, но идеальным подходом будет тот, который предложен в этом ответе Жасмит Каур

for view in cell.subviews {
    if let lable = view as? UILabel {
        lable.textColor = UIColor.red
     }
 }
Другие вопросы по тегам