我在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];
}
我尝试在swift中翻译它,但我对这一行有疑问:
return (UIView *)[[AAPLCollectionViewWrapper alloc] initWithCollectionView:collectionView mapping:mapping measuring:measuring];
在Swift中
return (CollectionViewWrapper(collectionView: collectionView, mapping: mapping, measuring: measuring) as! UIView
我有这个错误从'CollectionViewWrapper'转换为无关类型'UIView'总是失败
怎么了?如何将我的APPLCollectionViewWrapper转换为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中做同样的事情?
答案 0 :(得分:0)
我建议考虑“管道”模型,这样你的包装器必须是UICollectionView本身 - 需要从UICollectionView派生:
@interface AAPLCollectionViewWrapper : UICollectionView
//...
+ (UICollectionView *)wrapperForCollectionView:(UICollectionView *)collectionView mapping:(AAPLDataSourceMapping *)mapping
//...
答案 1 :(得分:0)
来自' CollectionViewWrapper'不相关的类型' UIView'总是 失败
编译器说它总是会失败但不会在运行时失败。如果它真的是一种UIView,它在运行时不会失败。 AAPLCollectionViewWrapper
是一个Objective-C表达式,UICollectionView
的扩展名可能是优雅的。