ios - Swift 4 中的 UICollectionViewController 未调用 cellForItemAt 函数
问题描述
它看起来很基本,但我不能让它在 Swift 4 中工作。
所以我有以下 UICollectionViewController 的实现
class TestController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.register(MyCell.self, forCellWithReuseIdentifier: "default")
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return collectionView.dequeueReusableCell(withReuseIdentifier: "default", for: indexPath)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return .init(width: view.frame.width, height: 100)
}
}
虽然... numberOfItems ...
方法被调用,但 for... cellForItemAt indexPath ...
没有。
我错过了什么?
这是单元格的代码
class MyCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .green
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
另外,我没有使用故事板,所以我在AppDelegate
课堂上按如下方式实例化这个控制器:
...
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow()
window?.makeKeyAndVisible()
window?.rootViewController = UINavigationController(rootViewController: TestController(collectionViewLayout: .init()))
return true
}
...
解决方案
代替
window?.rootViewController = UINavigationController(rootViewController: TestController(collectionViewLayout: .init()))
在 didFinishLaunchingWithOptions 方法中使用这个
window?.rootViewController = UINavigationController(rootViewController: TestController(collectionViewLayout: UICollectionViewFlowLayout()))
推荐阅读
- javascript - Javascript - 处理鼠标拖动事件
- json - 在 PRISM WPF 应用程序上下文中接收 HTTP JSON 请求的最佳解决方案是什么?
- flutter - How to update variable from TextFormField in flutter?
- phpstorm - PhpStorm 文件观察器“错误:找不到模块”在 rollupjs 脚本中带有 babel 插件(没有可用的可执行文件),插件全局安装
- flutter - 颤动中AutoCompleteTextField中的逗号分隔
- r - 如何在 R 中自定义 bin 图
- flutter - Flutter Bloc,Bloc 状态,导航?
- c# - 构建他人开发的 Windows 应用程序(x64)时在 VS 社区 2019 中编译失败
- python - Django REST 登录错误。我不知道该怎么办
- spring-boot - Spring Boot - 文件夹中的所有测试都从覆盖率报告中排除