我有一个String
扩展程序,我想在NSString
objective c
上使用它。由于swift中的String
为struct
,因此不会向objective c
公开。因此,为了从objective c
调用它,我在同一文件中的extension
上定义了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
中。然后我尝试使用htmlAttributedStringWithFont
objective c
班级调用NSString
方法
[str htmlAttributedStringWithFont:[UIFont systemFontSize]];
它给了我以下错误
No visible @interface for 'NSString' declares the selector 'htmlAttributedStringWithFont:'
我知道如何在String
Swift
Objective c NSString
中使用 Person food Amount
Mike Butter 3
Mike Milk 4
Mike Chicken 2
Tim Milk 4
John Chicken 2
扩展程序
答案 0 :(得分:0)