Swift 3警告:collectionView实例方法几乎匹配可选要求

3

我正在使用Xcode 8.1将我的项目转换为Swift 3,我的一个集合视图函数返回了一个警告信息,指示占用空间已经改变。代码如下:

 func collectionView(_ collectionView: UICollectionView, cellForItemAtIndexPath indexPath: IndexPath) -> UICollectionViewCell {

警告内容为:

实例方法CollectionView(:CellForItemAtIndexPath:)几乎匹配UICollectionViewDelegate协议的可选要求collectionView(:canFocusItemAt:)

我认为这个警告在这里是一个误导信息。我查看了API参考https://developer.apple.com/reference/uikit/uicollectionview/1618088-cellforitem,并发现

func cellForItem(at indexPath: IndexPath) -> UICollectionViewCell?

然而,我无法找到一个声明,它不会导致编译器错误并显示红点。

编辑:

在下面的答案之后,我将数据源添加到我的ViewController类中,如下所示:

class MyController: UIViewController,
                         UICollectionViewDelegateFlowLayout,
                         UICollectionViewDataSource,

然后在ViewDidLoad()中,我添加了myCollectionView.dataSource = self

现在我有了这个:

func collectionView(_ collectionView: UICollectionView,
                    cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

此视图控制器完全是通过代码构建的,并且尚未实现数据源,尽管在添加数据源后有关于 numberOfSectionsInCollectionView 的代码会导致编译器出现红色圆点。 这已更新为

func numberOfSections(in collectionView: UICollectionView) -> Int {

尝试将它们设置为“公共的”。 - Al___
1个回答

4

我认为这里的警告是一个误导。

事实并非如此。通常对待编译器应该是带着尊重的态度;它通常知道比你更多。你的 https://developer.apple.com/reference/uikit/uicollectionview/1618088-cellforitem 是个误导。

这个 是你想要的函数:

https://developer.apple.com/reference/uikit/uicollectionviewdatasource/1618029-collectionview

如您所见,签名为:

func collectionView(_ collectionView: UICollectionView, 
    cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

......这与您最初编写的内容略有不同。

另一个需要注意的是,您必须在 显式 采用 UICollectionViewDataSource 的类声明内进行此声明。唯一的例外是如果这是一个 UICollectionViewController,在这种情况下,它已经采用了 UICollectionViewDataSource —— 在这种情况下,编译器会告诉您添加 override 到您的声明中(并且您应该遵守)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接