【发布时间】:2019-01-25 11:12:36
【问题描述】:
这似乎很基本,但我无法在 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 ... 方法被调用,但... 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
}
...
【问题讨论】:
标签: ios swift uicollectionview swift4 uicollectionviewdelegate