Почему не работает CollectionView
У меня есть CollectionView с кнопками которые будут отображать время (Кликабельные).
Вот мой код:
import UIKit
class CreateWindow: UIViewController, UICollectionViewDelegateFlowLayout {
let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
var items = ["11:30","12:30","13:30","14:30","15:30","16:30"]
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.delegate = self
self.collectionView.dataSource = self
}
}
extension CreateWindow: UICollectionViewDataSource, UICollectionViewDelegate{
// MARK: - UICollectionViewDataSource protocol
// tell the collection view how many cells to make
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print(self.items.count)
return self.items.count
}
// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
print(self.items.count)
// get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! TimeCollection
// Use the outlet in our custom class to get a reference to the UILabel in the cell
cell.TimeLabel.text = self.items[indexPath.item]
cell.backgroundColor = UIColor.cyan // make cell more visible in our example project
return cell
}
// MARK: - UICollectionViewDelegate protocol
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// handle tap events
print("You selected cell #\(indexPath.item)!")
}
}
class TimeCollection: UICollectionViewCell {
@IBOutlet weak var TimeLabel: UILabel!
}
collectionView.delegate я пробовал и через код swift и через сам storyboard привязывал к ViewController.
При запуске срабатывает только функция кол-во ячеек, а функция их создания - нет (print ничего не выводит)
Кто нибудь знает как решить эту проблему?
Дополнительная информация:
Скриншот моих слоев (Collection не заполнена)

Зависимости Cell
Ответы (1 шт):
Скорее всего у вас не указан в сториборд Custom Class для ячейки - нужно дать понять collection view какой класс для ячейки использовать. После этого соедините @IBOutlet weak var TimeLabel: UILabel! с лейблом в ячейке в сториборд и все должно заработать
Дополнение
вот так нужно сделать
Дополнение 2
вот так выглядит в Debug View Hierarchy
Дополнение 3
посмотрите исходники сториборд (Open As - Source Code), есть ли там ваш класс ячейки customClass="TimeCollection". Иногда для его установки еще приходится нажимать Enter в поле ввода Custom Class
Дополнение 4
В целом, если не заработает, можно попробовать вынести ячейку в отдельный xib (да и вообще так лучше), тогда ее нужно будет зарегистрировать, в остальном все так же (я назвал класс TimeCollectionViewCell)
self.collectionView.delegate = self
self.collectionView.dataSource = self
self.collectionView.register(UINib.init(nibName: "TimeCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "cell")







