如何将对象 c 传输到 Swift aout collectionVIewLayout

How to transfer Object c to Swift aout collectionVIewLayout

我已将以下网站作为参考,并尝试将其转换为 Swift 代码。参考“collectioViewLayout”部分,我很难按顺序排列。

对此表示赞赏。UICollectionVIew circlesLayout

The original code is as below:-

- (CGSize)sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
if ([[self.collectionView.delegate class] conformsToProtocol:@protocol(UICollectionViewDelegateFlowLayout)]) {
    return [(id)self.collectionView.delegate collectionView:self.collectionView layout:self sizeForItemAtIndexPath:indexPath];
}
return CGSizeMake(0, 0);}

My revised swift code as follows:-

func sizeForItem(at indexPath: IndexPath?) -> CGSize {
    if type(of: collectionView.delegate) is UICollectionViewDelegateFlowLayout {
        if let indexPath = indexPath {
            return collectionView!.delegate?.collectionView!(collectionView!, layout: self, sizeForItemAt: indexPath) ?? CGSize.zero
        }
        return CGSize.zero
    }
    return CGSize(width: 0, height: 0)
}

但是,出现了一些错误。 (见下文)

Part 1) Cast from 'UICollectionViewDelegate?.Type' to unrelated type 'UICollectionViewDelegateFlowLayout' always fails

Part 2) Incorrect argument labels in call (have ':layout:sizeForItemAt:', expected':targetIndexPathForMoveFromItemAt:toProposedIndexPath:')

有没有人可以指导我如何将这些问题修复为正确的 swift 代码?

Objective-C 代码检查 collectionView.delegate 的类型,但在 Swift 中你必须做一个转换来告诉编译器你确定它确实是 UICollectionViewDelegateFlowLayout{

func sizeForItem(at indexPath: IndexPath?) -> CGSize {
    // "as?" does the cast, evaluating the expression to nil if it fails.
    if let delegate = collectionView!.delegate as? UICollectionViewDelegateFlowLayout,
        // you can combine these two checks into one if statement. Just separate them with ","
        let indexPath = indexPath {
        return delegate.collectionView?(collectionView, layout: self, sizeForItemAt: indexPath) ?? .zero
    }
    return .zero
}