2017-08-28 78 views
0

我有一個String擴展名,我想在NSString上使用objective c。由於swift中的Stringstruct所以它沒有暴露於objective c。所以爲了從objective c中調用它,我在NSString上定義了一個extension在同一個文件中。從目標C調用在Swift中定義的NSString擴展名

public extension NSString { 

     func htmlAttributedStringWithFont(font: UIFont, size fontSize: CGFloat = 17.0) -> NSAttributedString? { 
      let str = self as String 
      return str.htmlAttributedStringWithFont(font: font) 
     } 

    } 



    extension String { 

     /// Converts an HTML String to NSAttributedString 
     /// 
     /// - Returns: NSAttributedString? 
     func htmlAttributedString() -> NSAttributedString? { 
      guard let data = self.data(using: .utf16, allowLossyConversion: false) else { 
       return nil 
      } 
      guard let html = try? NSMutableAttributedString(
       data: data, 
       options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], 
       documentAttributes: nil) else { return nil } 
      return html 
     } 

     /// returns and NSAttributedString optional from HTML content after applying specific font and size 
     /// 
     /// - Parameters: 
     /// - font: Font to be applied on the returned string 
     /// - fontSize: Size to be applied on the returned string 
     /// - Returns: NSAttributedString? 
     func htmlAttributedStringWithFont(font: UIFont, size fontSize: CGFloat = 17.0) -> NSAttributedString? { 
      let string = self.appending(String(format: "<style>body{font-family: '%@'; font-size:%fpx;}</style>", font.fontName, fontSize)) 
      return string.htmlAttributedString() 
     } 
} 

以上兩個擴展名在String+Extension.swift。然後我試圖從我objective cNSString

[str htmlAttributedStringWithFont:[UIFont systemFontSize]]; 

調用htmlAttributedStringWithFont方法它給了我下面的錯誤

No visible @interface for 'NSString' declares the selector 'htmlAttributedStringWithFont:' 

任何想法我如何能在Swift使用String擴展從Objective c NSString

+0

我相信具有默認參數的函數不會暴露給objc。嘗試編寫'@objc func htmlAttributedStringWithFont(font:UIFont,size fontSize:CGFloat = 17.0) - > NSAttributedString?'並檢查它是否返回錯誤。 – Adamsor

+0

仍然是一樣的錯誤。 – Madu

+1

https://stackoverflow.com/questions/27097688/can-objective-c-code-call-swift-extension-on-class 看起來像swift/xcode可能會生成需要導入的obj-c頭文件 – solenoid

回答

0
  1. 如果您在同一個項目中使用Swift和Objective-C文件,那麼有一定的文件名爲YourProjectName-Swift.h它是由xCode自動爲您創建的。
  2. 假設您剛創建或更新了一個Swift擴展。
  3. 這應該更新爲yourprojectname-Swift.h自動 然後在你的Objective-C類,你可以使用 銀行代碼導入這個頭文件(#進口「爲yourprojectname-Swift.h」)。
  4. 爲了以防萬一,如果沒有,那麼你可以手動 更新這個頭文件。