Swift 3警告Func Collection View实例方法几乎符合可选要求



我将项目转换为Xcode 8.1中的Swift 3,我的收集视图功能之一正在返回警告消息,表明足迹已更改。代码是

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

警告是

实例方法collectionView(:CellForiteMatindExpath :)几乎匹配可选要求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 {

我相信警告是这里的红鲱鱼

好吧,不是。通常,处理编译器的方法是尊重的。通常,它比您了解得多。您的https://developer.apple.com/reference/uikit/uicollectionview/1618088-cellforitem是红鲱鱼。

是您想要的功能:

您可以看到,签名是:

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

...这与您最初写的内容明显不同。

要注意的另一件事是,您必须在明确采用UicollectionViewDataSource的类声明中进行此声明。唯一的例外是,如果这是一个UicollectionViewController,在这种情况下,它已经采用了UicollectionViewDataSource,在这种情况下,编译器会告诉您将override添加到您的声明中(您应该遵守)。

最新更新