2012-07-18 76 views
2

我正在開發一個iPhone應用程序,用於從Twitter獲取推文。我通過Json做到了這一點,並且一切正常。我在尋找每一條推文,看看它是否包含標籤,然後改變特定標籤的顏色。檢查字符串是否包含哈希標籤,然後更改哈希標籤顏色

例如:「這是一個鳴叫#MYTWEET」

所以我想「這是推特」是一種顏色,「#MYTWEET」是一個單獨的顏色。我知道如何搜索哈希標籤,但我似乎無法弄清楚如何只改變下面的文本。

編輯:

沒有特定主題標籤要麼,所以它需要能夠改變所有顯示的主題標籤的顏色。

回答

11
NSString *tweet = @"This is a tweet #MYTWEET"; 

NSArray *words = [tweet componentsSeparatedByString:@" "]; 

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:tweet]; 

for (NSString *word in words) { 

    if ([word hasPrefix:@"#"]) { 

     // Colour your 'word' here 
     NSRange matchRange = [tweet rangeOfString:word]; 

     [attrString addAttribute:kCTForegroundColorAttributeName 
          value:[UIColor redColor] 
          range:matchRange]; 
     // Remember to import CoreText framework (the constant is defined there) 

    } 
} 

//Display your attributed string ... 

注意:如果你想知道如何顯示字符串,這裏是一個很好的開源項目:https://github.com/AliSoftware/OHAttributedLabel

+0

我是否需要導入框架?我得到一個錯誤kCTForegroundColorAttributeName。 – Sean 2012-07-18 20:12:59

+0

@Sean是的,你需要導入'CoreText'框架,對不起,我忘了提及 – Alladinian 2012-07-18 20:13:45

+0

非常感謝! – Sean 2012-07-18 20:25:58

0
NSRange hashLocation = [tweetString rangeOfString:@"#MYTWEET"]; 
if (hashLocation.location == NSNotFound) 
     { 
      //do coloring stuff here 
     } 

編輯:我想你只是想着色一個子串。這在iOS的當前版本中是不可能的,但是您可以通過爲每種顏色創建一個標籤並將它們放在彼此的旁邊,使其看起來像一行文本一樣來實現。

+0

雖然它可以是任何hashtag。對不起,我應該更好地解釋。 – Sean 2012-07-18 18:30:20

+0

只是做了一個編輯。我想這就是你要找的。 – 2012-07-18 18:31:25

0

如果您使用的是UILabel來顯示字符串,你可以使用ActiveLabel.swift這是一個UILabel插入式替換支持在Swift中編寫的Hashtags(#),提及(@)和URL(http://)

enter image description here

更改的用戶名,井號標籤和鏈接的顏色是如此簡單:

label.textColor = .blackColor() 
label.hashtagColor = .blueColor() 
label.mentionColor = .greenColor() 
label.URLColor = .redColor() 

免責聲明:我是庫的作者。

+1

這也應該爲UITextView :) – 2015-12-15 18:53:57