2017-01-20 60 views
2

我正在將一個swift項目轉換爲目標c,但我遇到了一些麻煩,因爲我不知道如何轉換後續代碼。請幫幫我。謝謝!如何將此Swift語法轉換爲Objective C?

public enum UPCarouselFlowLayoutSpacingMode { 
    case fixed(spacing: CGFloat) 
    case overlap(visibleOffset: CGFloat) 
} 

fileprivate var currentPage: Int = 0 { 
    didSet { 
     let character = self.items[self.currentPage] 
     self.infoLabel.text = character.name.uppercased() 
     self.detailLabel.text = character.movie.uppercased() 
    } 
} 
+2

的第一個片段,不能轉換成Objective-C的,因爲相關類型的枚舉不可在ObjC中獲得。第二個片段可以通過實現屬性的顯式設置器來轉換。 – vadian

+1

將Objective-C轉換爲Swift比試圖從Swift到Objective C進行一對一轉換要容易得多。Swift的枚舉是獨特而強大的,我懷疑你會找到一種簡單的方法將它轉換爲Swift –

回答

5

第一(一個enum具有相關聯的值)具有在Objective-C沒有直接的等價物。爲了您的具體的例子,你可以使用這樣的事情:

typedef NS_ENUM(NSInteger, UPCarouselFlowLayoutSpacingMode) { 
    UPCarouselFlowLayoutSpacingModeFixed, 
    UPCarouselFlowLayoutSpacingModeOverlap 
}; 

typedef struct { 
    UPCarouselFlowLayoutSpacingMode mode; 
    CGFloat amount; 
} UPCarouselFlowLayoutSpacing; 

你只繞過UPCarouselFlowLayoutSpacing類型的值。您可以創建助手功能,以便更容易地創建這些功能。

UPCarouselFlowLayoutSpacing UPCarouselFlowLayoutSpacingMakeFixed(CGFloat spacing) { 
    UPCarouselFlowLayoutSpacing value; 
    value.mode = UPCarouselFlowLayoutSpacingModeFixed; 
    value.amount = spacing; 
    return value; 
} 

UPCarouselFlowLayoutSpacing UPCarouselFlowLayoutSpacingMakeOverlap(CGFloat visibleOffset) { 
    UPCarouselFlowLayoutSpacing value; 
    value.mode = UPCarouselFlowLayoutSpacingModeOverlap; 
    value.amount = visibleOffset; 
    return value; 
} 

對於第二個,您可以覆蓋你的Objective-C類的currentPage屬性的setter方法:

- (void)setCurrentPage:(NSInteger)page { 
    _page = page; 

    MovieCharacter *character = self.items[page]; 
    self.infoLabel.text = character.name.localizedUppercaseString; 
    self.detailLabel.text = character.movie.localizedUppercaseString; 
} 
+4

擊敗我:| – Alexander

+1

謝謝!我會嘗試 –

相關問題