【问题标题】:"Missing argument for parameter 'for' in call"“调用中参数'for'缺少参数”
【发布时间】:2016-09-07 06:07:27
【问题描述】:

在 swift3 中编码时,我想使用自定义协议和泛型来重用集合视图单元格。我知道这是重用单元格的标准方式:

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

    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TacoCell", for: indexPath) as? TacoCell {

        cell.configureCell(taco: ds.tacoArray[indexPath.row])

        return cell
    }

    return UICollectionViewCell()
}

但每次我尝试这样做时:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as TacoCell
    cell.configureCell(taco: ds.tacoArray[indexPath.row])
    return cell
}

编译器抱怨我有一个“在调用中缺少参数'for'的参数”......在这种情况下,参数是“forIndexPath”

仅供参考...

我有用于重用单元格和加载笔尖的自定义扩展。代码如下:

ReusableView 类

import UIKit

protocol ReusableView: class  { }

extension ReusableView where Self: UIView {

    static var reuseIdentifier: String {
        return String.init(describing: self)
    }
}

NibLoadableView 类

import UIKit

protocol NibLoadableView: class { }

extension NibLoadableView where Self: UIView {

    static var nibName: String {
        return String.init(describing: self)
    }
}

这是我的 UICollectionView 扩展

import UIKit

extension UICollectionView {
    func register<T: UICollectionViewCell>(_: T.Type) where T: ReusableView, T: NibLoadableView {

    let nib = UINib(nibName: T.nibName, bundle: nil)
    register(nib, forCellWithReuseIdentifier: T.reuseIdentifier)
}


func dequeueReusableCell<T: UICollectionViewCell>(forIndexPath indexPath: NSIndexPath) -> T where T: ReusableView {

    guard let cell = dequeueReusableCell(withReuseIdentifier: T.reuseIdentifier, for: indexPath as IndexPath) as? T else {
        fatalError("Could not dequeue cell with identifier: \(T.reuseIdentifier)")
    }

    return cell
    }
}

extension UICollectionViewCell: ReusableView { }

【问题讨论】:

  • 您能否提供一个链接来描述使用(仅)forIndexPathdequeueReusableCell?另外,您是否尝试过将forIndexPath 替换为for
  • 对不起@Evert...我对 UICollectionView 进行了扩展,我正在使用我的“覆盖”dequeueReusableCell 方法,该方法具有参数forIndexPath。我的假设是因为它被接受为扩展,我可以用它来重用我的单元格。我也包含了上面的扩展代码

标签: swift3 xcode8-beta6


【解决方案1】:

问题在于,您的 Swift 3.0 代码旁边还有一些 Swift 2.2 代码,编译器在尝试选择要调用的方法时会感到困惑,因为没有完全匹配的方法。

您的cellForItemAt 方法使用集合视图中的IndexPath 调用您自己的dequeueReusableCell() 扩展方法。但是,您编写的扩展方法期望接收NSIndexPath,这是一个微妙的不同。

修改你的扩展方法,问题应该会解决:

func dequeueReusableCell<T: UICollectionViewCell>(forIndexPath indexPath: IndexPath) -> T where T: ReusableView {

【讨论】:

  • 谢谢@TwoStraws!这似乎让它继续下去
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-07-01
  • 2017-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多