簡體   English   中英

NSString:剝離並為該段制作帶有顏色的屬性字符串?

[英]NSString: strip out <b></b> and make an attributed string with color for that segment?

假設我有一個字符串:

這是一個<b>簡單的</b>字符串。

我需要去掉 < b >,(抱歉 b 和尖括號之間沒有空格,由於某種原因預覽沒有顯示它),也讓“簡單”這個詞加粗,我的想法是:

  1. 用空格替換尖括號和 br
  2. 使“簡單”段具有屬性

問題是標簽去掉后,我還需要知道單詞的位置,我是不是先記住'simple'的位置,去掉后,location-4應該是'simple'的新位置嗎? 有沒有更好的辦法? 或者甚至將 html 標簽轉換為屬性?

謝謝

編輯:應該是 b 而不是 br

iOS 7 中有可用的 API 使這變得非常容易。 它將(可能的)HTML 文本的NSString轉換為NSAttributedString

NSDictionary *options = @{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType };

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithData:[myHTMLString dataUsingEncoding:NSUTF8StringEncoding] options:options documentAttributes:nil error:nil];

它甚至會保留任何應用的內嵌 CSS,甚至是background-color

請注意,如果 HTML 文本中未指定字體和字體大小,則默認值為 Times New Roman 12。您可以以這種方式指定: <style>body { font-family:-apple-system; font-size:14px; }<style> <style>body { font-family:-apple-system; font-size:14px; }<style> <style>body { font-family:-apple-system; font-size:14px; }<style> 如果您不通過 CSS 指定字體,您仍然可以覆蓋字體,但您需要手動處理粗體、斜體等,否則如果您為整個字符串設置字體,格式將丟失。 一種方法是enumerateAttribute: NSFontAttributeName在可變屬性字符串上查找字體名稱中的“粗體”等,如果找到,則將該range替換為所需的字體,例如用戶的首選字體和大小,但粗體等版本它,並繼續用從枚舉中獲得的每個range替換字體。

目前的答案是可以的,我已經 +1 了。 然而,這只是一個線索,並不是真正的解決方案。 如果您正在尋找 OP 問題的解決方案,請查看此處

您應該關注以下幾點:

首先實現這些方法:

- (NSString *)styledHTMLwithHTML:(NSString *)HTML {
    NSString *style = @"<meta charset=\"UTF-8\"><style> body { font-family: 'HelveticaNeue'; font-size: 20px; } b {font-family: 'MarkerFelt-Wide'; }</style>";

    return [NSString stringWithFormat:@"%@%@", style, HTML];
}

- (NSAttributedString *)attributedStringWithHTML:(NSString *)HTML {
    NSDictionary *options = @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType };
    return [[NSAttributedString alloc] initWithData:[HTML dataUsingEncoding:NSUTF8StringEncoding] options:options documentAttributes:NULL error:NULL];
}

以后像這樣使用它們:

// This is a string that you might find in your model
NSString *html = @"This is <b>bold</b>";

// Apply some inline CSS
NSString *styledHtml = [self styledHTMLwithHTML:html];

// Generate an attributed string from the HTML
NSAttributedString *attributedText = [self attributedStringWithHTML:styledHtml];

// Set the attributedText property of the UILabel
label.attributedText = attributedText;

使用此方法( Swift 5 ):

extension Swift {
    // Color all strings between two tags and remove the tags
    mutating func colorSubstringsBetweenTags(start: String, end: String, color: UIColor, font: UIFont? = nil) -> NSAttributedString {
        var string = self
        let attribute = NSMutableAttributedString(string: string)
        
        while let openedEm = string.range(of: start, range: string.startIndex..<string.endIndex) {
            let substringFrom = openedEm.upperBound
            guard let closedEm = string.range(of: end, range: openedEm.upperBound..<string.endIndex) else { return attribute }
            let substringTo = closedEm.lowerBound
            let nsrange = NSRange(substringFrom..<substringTo, in: string)
            if let font = font { attribute.addAttributes([.font: font], range: nsrange) }
            attribute.addAttribute(.foregroundColor, value: color, range: nsrange)
            attribute.mutableString.replaceCharacters(in: NSRange(closedEm, in: string), with: "")
            attribute.mutableString.replaceCharacters(in: NSRange(openedEm, in: string), with: "")
            string = attribute.mutableString as String
        }
        
        return attribute
    }
}

用法:

 var text = "some text with <b>tags</b> or other <b>TAG</b>"
 yourLabel.attributedText = text.colorSubstringsBetweenTags(start: "<b>", end: "</b>", color: .red)

類似於剛剛針對最新 swift 版本更新的 Michael 的回答,

extension UILabel {
    func setHTMLFromString(htmlText: String) {
        // Apply some inline CSS
        let style = "<meta charset=\"UTF-8\"><style> body { font-family: 'TheSansArabic-Plain'; font-size: 12px; } b {font-family: 'TheSansArabic-Bold'; font-size: 12px; } </style>"
        let styledHtml = style + htmlText
        // Generate an attributed string from the HTML
        let attributedText = try? NSAttributedString(data: styledHtml.data(using: .utf8)!, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
        // Set the attributedText property of the UILabel
        self.attributedText = attributedText
    }
}

像這樣在你的代碼中使用,

override func viewDidLoad() {
    super.viewDidLoad()
    label.setHTMLFromString(htmlText: "This is <b>BOLD text</b>")
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM