我如何传递一个动态类型的参数到一个函数在Swift?



我有一个接收特定类类型参数的函数,但我想使它动态,以便我也可以传递来自另一个类名的参数。

func unselectedTopCell(cell: SearchExploreCollectionViewCell) {
let color = UIColor.init(named: "textBlack") ?? .black
let borderColor = color.withAlphaComponent(0.12)
let textColor = color.withAlphaComponent(0.87)
cell.cellBGView?.borderColor = borderColor
cell.cellBGView?.borderWidth1 = 1
cell.titleLabel?.textColor = textColor
}

现在我想重用这个函数为另一个集合视图单元格,但我如何传递其他类名而不是"SearchExploreCollectionViewCell"在打电话的时候?

在一个公共协议下使你要作为参数传递的类保持一致。通过这样做,您可以将参数的数据类型作为协议,并且可以在其位置使用符合该协议的任何类。

如果我理解正确,你可以修复这个:

首先,你可以为它写一个扩展。这让事情变得容易多了。

public extension UICollectionView {
func cellWithIdentifierAndIndexPath<T:UICollectionViewCell>(cell:T.Type,indexPath:IndexPath) -> T {
let genericCell = self.dequeueReusableCell(withIdentifier: T.className, for: indexPath) as! T
return genericCell
}
}

然后,在cellForItemAt函数中:

var cell = UICollectionViewCell()
switch yourCellType {
case searchExplore:
cell = collectionView.cellWithIdentifierAndIndexPath(cell: SearchExploreCollectionViewCell.self, indexPath: indexPath)
case someThingElse:
cell = collectionView.cellWithIdentifierAndIndexPath(cell: SomeThingElse.self, indexPath: indexPath)
default:
cell = collectionView.cellWithIdentifierAndIndexPath(cell: NoDataCell.self, indexPath: indexPath)
}
return cell

重要提示:不要忘记设置单元格的可重用id作为单元格的类名。

例如,如果您有一个单元格的名称为"NoDataCell",您应该使用"NoDataCell"作为重用标识符。

最新更新