I have a a String
extension which i want to use on NSString
from objective c
. As String
in swift is a struct
so its not exposed to objective c
. So in order to call it from objective c
i defined an extension
on NSString
in the same file.
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()
}
}
The above two extensions are in the same file String+Extension.swift
. I then tried to call the htmlAttributedStringWithFont
method from my objective c
class with NSString
[str htmlAttributedStringWithFont:[UIFont systemFontSize]];
it gives me the following error
No visible @interface for 'NSString' declares the selector 'htmlAttributedStringWithFont:'
Any idea how i can use String
extension in Swift
from Objective c NSString