首页 > 解决方案 > 无法将集合视图连接到视图控制器代码。'错误无法识别的选择器发送到实例'

问题描述

我正在尝试向我的自定义视图控制器添加一个名为“cardsViewController”的集合视图。当我运行构建时,我收到错误 [UIViewController collectionView:numberOfItemsInSection:]: unrecognized selector sent to instance

我已将集合视图的数据源和委托连接到情节提要中的视图控制器,并在代码中的类名之后添加了“UICollectionViewDataSource,UICollectionViewDelegate”。我还通过将“CardsViewController”(与代码文件同名)添加到视图控制器的自定义类字段来将情节提要中的视图控制器连接到代码。

import UIKit

class CardsViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 4
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        var cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)

        return cell
    }

}

我希望 xcode 能够识别视图控制器代码文件负责控制集合视图。

Cards View Controller 的身份检查员

集合视图的连接检查器

标签: swiftxcodeviewcontroller

解决方案


当您在界面生成器中设置错误的视图控制器时,通常会发生这种情况。确保Custom ClassinIdentity Inspector与您的视图控制器类名 ( CardsViewController) 完全匹配。


推荐阅读