我有一个带有显示时间的按钮的 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 代码和故事板本身绑定到ViewController
. 启动时,只有单元格数量功能起作用,但创建它们的功能不起作用(print
不显示任何内容)有谁知道如何解决这个问题?
附加信息:
单元依赖
最有可能的是,您没有在情节提要中指定单元格的自定义类 - 您需要让集合视图清楚地为单元格使用哪个类。之后,
@IBOutlet weak var TimeLabel: UILabel!
与情节提要中单元格中的标签连接,一切正常添加
这是应该怎么做的
补充 2
这就是调试视图层次结构中的样子
补充 3
查看情节提要的源代码(Open As - Source Code),看看你的单元格类是否存在
customClass="TimeCollection"
。有时您仍然需要在 Custom Class 输入字段中按 Enter 来安装它。补充 4
一般来说,如果不起作用,你可以尝试将单元格移动到单独的xib(一般情况下更好),然后它需要注册,否则一切都一样(我命名的类
TimeCollectionViewCell
)