2013-05-07 33 views
1

我從Web服務獲取數據,結果包含一些HTML標記,然後嘗試轉換。例如,我想用換行符替換<P>標籤,將<STRONG>替換爲粗體文本。替換具有文本屬性的HTML標記

任何人都可以幫助我嗎?我已經研究出如何替換文字 - 我想我已經走到了一半。

if([key isEqualToString:@"Description"]){ 
      txtDesc.text=[results objectForKey:key]; 
      NSString * a = txtDesc.text; 

      NSString * b = [a stringByReplacingOccurrencesOfString:@"<strong>" withString:@"STRONG TAG"]; 
      b = [b stringByReplacingOccurrencesOfString:@"<\\/p>" withString:@""]; 
      b = [b stringByReplacingOccurrencesOfString:@"</p>" withString:@""]; 

      txtDesc.text=b; 

     } 
+0

講座4回答說,使用網頁視圖,但我不想。 – iYugShell 2013-05-07 19:08:17

回答

0

作爲所述需要使用NSAttributedString

它實現你將通過屬性的一個NSDictionary和範圍(characteres的)以下的方法來接收屬性之前

- (void)setAttributes:(NSDictionary *)attributes range:(NSRange)range; 

NSDictionary中的一個例子是:

@{ NSFontAttributeName: [UIFont systemFontOfSyze:24], NSForegroundColorAttributeName: [UIColor greenColor]} 

你可以尋找更多的信息,對蘋果的文檔 https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSAttributedString_Class/Reference/Reference.html

或在驚人 iPhone應用程序開發過程中的斯坦福 http://www.stanford.edu/class/cs193p/cgi-bin/drupal/downloads-2013-winter

+0

感謝這正是我正在尋找的東西。感謝您抽出寶貴的時間。 – iYugShell 2013-05-07 21:47:25

4

字符串沒有粗體等屬性。字符串只包含字符,包括斷路器。如果你想豐富你的字符串的屬性,看看NSAttributedString。

更新: 對於我們這些,誰也看不到,爲什麼歸因字符串的解決方案,一段簡單的代碼:

- (NSAttributedString*)attributedStringByReplaceHtmlTag:(NSString*)tagName withAttributes:(NSDictionary*)attributes 
{ 
    NSString *openTag = [NSString stringWithFormat:@"<%@>", tagName]; 
    NSString *closeTag = [NSString stringWithFormat:@"</%@>", tagName]; 
    NSMutableAttributedString *resultingText = [self mutableCopy]; 
    while (YES) { 
     NSString *plainString = [resultingText string]; 
     NSRange openTagRange = [plainString rangeOfString:openTag]; 
     if (openTagRange.length==0) { 
      break; 
     } 

     NSRange searchRange; 
     searchRange.location = openTagRange.location+openTagRange.length; 
     searchRange.length = [plainString length]-searchRange.location; 
     NSRange closeTagRange = [plainString rangeOfString:closeTag options:0 range:searchRange]; 

     NSRange effectedRange; 
     effectedRange.location = openTagRange.location+openTagRange.length; 
     effectedRange.length = closeTagRange.location - effectedRange.location; 

     [resultingText setAttributes:attributes range:effectedRange]; 
     [resultingText deleteCharactersInRange:closeTagRange]; 
     [resultingText deleteCharactersInRange:openTagRange]; 

    } 

    return resultingText; 
} 

但我沒有測試好,因爲我已經準備燴飯,而編程。 ;-)

+0

他必須從html字符串中解析標籤,並將相應的屬性設置爲NSAttributedString的實例。我的答案的相關部分是:「你不能用NSString做這個。」 – 2013-05-07 20:20:16

+0

我發現這非常有幫助,因爲我不想實現一個耗時且以各種不同方式工作的完整HTML解析器。這完全符合我在之後將特定的包裝詞/ s轉換爲屬性版本。欣賞它! – Tom 2013-05-16 05:18:43

+0

這個真的很好! – kanstraktar 2016-03-03 16:41:02