Xcode 13中UICollectionView方法失效,求替代方案
UICollectionView numberOfItemsInSection 无法调用的解决办法(Xcode 13)
你注释掉的numberOfItemsInSection是UICollectionViewDataSource协议的必填方法,Xcode 13并没有提供替代它的API,CollectionView必须通过这个方法知道要渲染多少个单元格。以下是解决步骤:
- 取消
numberOfItemsInSection方法的注释,移除代码里的#标记(这是你手动添加的注释符号) - 在
viewDidLoad中给CollectionView设置代理和数据源(前提是你已经通过Storyboard或代码创建了CollectionView的引用) - 检查单元格注册:确保复用标识符"cell"和
MyCollectionCell的注册信息完全匹配(可以在Storyboard中设置,也可以通过代码注册) - 可选但建议:显式实现
numberOfSections方法,明确Section数量
修正后的完整代码
import UIKit class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { var shoppingapp: [String] = ["cher", "sale Small", "shoes"] // 假设已通过Storyboard连接CollectionView的IBOutlet @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() // 设置代理与数据源 collectionView.delegate = self collectionView.dataSource = self // 若未在Storyboard注册单元格,需手动注册 // collectionView.register(MyCollectionCell.self, forCellWithReuseIdentifier: "cell") } // 恢复必填的单元格数量方法 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return shoppingapp.count } // 显式指定Section数量(默认返回1,可选) func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MyCollectionCell cell.shoppinfappimage.image = UIImage(named: shoppingapp[indexPath.row] + ".jpeg") cell.shoppinfappimage.layer.cornerRadius = 50.0 return cell } }
额外注意点
- 确认
MyCollectionCell类与Storyboard中的单元格正确关联,shoppinfappimage的IBOutlet已连接成功 - 图片文件名需和数组元素拼接".jpeg"后的名称完全一致,注意大小写、空格等细节
- 检查CollectionView的约束设置,确保它在屏幕范围内可见
内容的提问来源于stack exchange,提问作者Utsav Gabani
相关产品推荐
相关产品推荐

