簡體   English   中英

Swift的Object Casting / ObjectiveC

[英]Object Casting / ObjectiveC from Swift

我在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];

在斯威夫特

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

我怎樣才能迅速做出同樣的事情?

我建議考慮“管道”模型,以便您的包裝器必須是UICollectionView本身-需要從UICollectionView派生:

@interface AAPLCollectionViewWrapper : UICollectionView
//...

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

從“ CollectionViewWrapper”強制轉換為不相關的類型“ UIView”總是失敗

編譯器說它將始終失敗,但不會在運行時失敗。 如果確實是一種UIView,它在運行時不會失敗。 而且AAPLCollectionViewWrapper是一個Objective-C表達式,也許UICollectionView擴展會很優雅。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM