gpt4 book ai didi

objective-c - 来自 Swift 的对象转换/ObjectiveC

转载 作者:搜寻专家 更新时间:2023-11-01 05:36:42 24 4
gpt4 key购买 nike

我在 Objective C 中有这段代码(它是 Apple AdvancedCollectionView 源代码的摘录)

@interface AAPLCollectionViewWrapper : NSObject

+ (UIView *)wrapperForCollectionView:(UICollectionView *)collectionView mapping:(AAPLDataSourceMapping *)mapping
{
if (!collectionView)
return nil;

BOOL measuring = NO;

if ([collectionView isKindOfClass:[AAPLCollectionViewWrapper class]])
measuring = ((AAPLCollectionViewWrapper *)collectionView).measuring;

return (UIView *)[[AAPLCollectionViewWrapper alloc] initWithCollectionView:collectionView mapping:mapping measuring:measuring];
}

我尝试快速翻译它,但我对这一行有疑问:

return (UIView *)[[AAPLCollectionViewWrapper alloc] initWithCollectionView:collectionView mapping:mapping measuring:measuring];

在 swift

return (CollectionViewWrapper(collectionView: collectionView, mapping: mapping, measuring: measuring) as! UIView

我有这个错误从“CollectionViewWrapper”到无关类型“UIView”的转换总是失败

怎么了?如何将我的 APPCollectionViewWrapper 转换为 UIView?

已更新

我想我需要使用多态性,在原始源代码中,我发现了这条评论:

/// An object that pretends to be either a UITableView 
/// or UICollectionView that handles transparently mapping from local to global index paths
@interface AAPLCollectionViewWrapper : NSObject

所以在源代码中,AAPLCollectionViewWrapper 是一个NSObject,函数wrapperForCollectionView 返回一个UIView,然后它被转换为一个UICollectionView

.h

/// An object that pretends to be either a UITableView or UICollectionView that handles transparently mapping from local to global index paths
@interface AAPLCollectionViewWrapper : NSObject

/// Factory method that will determine whether the wrapper is measuring based on the collection view. If the collectionView is actually an instance of AAPLCollectionViewWrapper, the value will be pulled from the collectionView. Otherwise, the default is NO.
+ (__kindof UIView *)wrapperForCollectionView:(UICollectionView *)collectionView mapping:(nullable AAPLDataSourceMapping *)mapping;

+ (__kindof UIView *)wrapperForCollectionView:(UICollectionView *)collectionView mapping:(nullable AAPLDataSourceMapping *)mapping measuring:(BOOL)measuring;

@property (nonatomic, strong, readonly) UICollectionView *collectionView;
@property (nullable, nonatomic, strong, readonly) AAPLDataSourceMapping *mapping;

@property (nonatomic, readonly) BOOL measuring;

@end

如何在 swift 中制作同样的东西?

最佳答案

我建议考虑“管道”模型,因此您的包装器必须是 UICollectionView 本身——需要从 UICollectionView 派生:

@interface AAPLCollectionViewWrapper : UICollectionView
//...

+ (UICollectionView *)wrapperForCollectionView:(UICollectionView *)collectionView mapping:(AAPLDataSourceMapping *)mapping
//...

关于objective-c - 来自 Swift 的对象转换/ObjectiveC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37181986/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com