0
我有一個String
擴展名,我想在NSString
上使用objective c
。由於swift中的String
是struct
所以它沒有暴露於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 c
類NSString
[str htmlAttributedStringWithFont:[UIFont systemFontSize]];
調用htmlAttributedStringWithFont
方法它給了我下面的錯誤
No visible @interface for 'NSString' declares the selector 'htmlAttributedStringWithFont:'
任何想法我如何能在Swift
使用String
擴展從Objective c NSString
我相信具有默認參數的函數不會暴露給objc。嘗試編寫'@objc func htmlAttributedStringWithFont(font:UIFont,size fontSize:CGFloat = 17.0) - > NSAttributedString?'並檢查它是否返回錯誤。 – Adamsor
仍然是一樣的錯誤。 – Madu
https://stackoverflow.com/questions/27097688/can-objective-c-code-call-swift-extension-on-class 看起來像swift/xcode可能會生成需要導入的obj-c頭文件 – solenoid