swift - 无法将 Collection View 连接到 View Controller 代码。 'Error unrecognized selector sent to instance'

标签 swift xcode viewcontroller

我正在尝试将 Collection View 添加到名为“cardsViewController”的自定义 View Controller 中。当我运行构建时,出现错误 [UIViewController collectionView:numberOfItemsInSection:]: 无法识别的选择器发送到实例

我已将 Collection View 的数据源和委托(delegate)连接到 Storyboard中的 View Controller ,并在代码中的类名后面添加了“UICollectionViewDataSource、UICollectionViewDelegate”。我还通过将“CardsViewController”(与代码文件同名)添加到 View Controller 的自定义类字段,将 Storyboard中的 View Controller 连接到代码。

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 能够识别 View Controller 代码文件负责控制 Collection View 。

identity inspector of Cards View Controller

connections inspector of the collection view

最佳答案

当您在界面构建器中设置错误的 View Controller 时,通常会发生这种情况。确保 Identity Inspector 中的Custom Class 与您的 View Controller 类名称 (CardsViewController) 完全匹配。

关于swift - 无法将 Collection View 连接到 View Controller 代码。 'Error unrecognized selector sent to instance',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55583807/

相关文章:

iOS viewController 和DetailViewController 流程​​/设计

swift - 当我的 ViewController 嵌入到 UINavigationController 中时,如何对值进行排序?

swift : How to instantiate a new view controller with separate delegate

ios - 在WebView上加载FTP服务器中存储的图像/文件

ios - 将 UIApplicationDelegate 方法转换为 RxSwift Observables

xcode - 如何在 Xcode 中更改 Git 的用户名?

xcode - 如何获取 “Developer ID Application”或 “Developer ID Installer”证书的私钥?

ios - 第一次应用程序 Xcode 10 和 iOS 未运行

ios - 将对象从 Parse 查询传递到 UIContainerView 从父 View

ios - 如何使用 UIPanGestureRecognizer 设置拖动控件的边界?