【发布时间】: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 { }
【问题讨论】:
-
您能否提供一个链接来描述使用(仅)
forIndexPath的dequeueReusableCell?另外,您是否尝试过将forIndexPath替换为for? -
对不起@Evert...我对 UICollectionView 进行了扩展,我正在使用我的“覆盖”
dequeueReusableCell方法,该方法具有参数forIndexPath。我的假设是因为它被接受为扩展,我可以用它来重用我的单元格。我也包含了上面的扩展代码
标签: swift3 xcode8-beta6