You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 21:30:53