[英]Make the specific string Pattern bold and blue in UILable
我有一個程序,其中我從Twitter獲得推文,並在UITableviewcell
顯示它們。 現在的問題是,我必須將所有推特名稱設為粗體和bule,並在原始推文中以bule和粗體名稱顯示它們。 例如我有這樣的推文
MT @OraTV
:偷窺: @tomgreenlive @TheoVon & @DavidBegnaud
談論麥莉的#twerking #Batfleck &more
內容
因此,所有以@ should be bold and bule.
開頭的名稱@ should be bold and bule.
我使用此代碼提取以@開頭的所有名稱,但不知道如何將它們加粗並在單個uitableviewcell中顯示它們
NSString * aString =twitterMessage
NSMutableArray *substrings = [NSMutableArray new];
NSScanner *scanner = [NSScanner scannerWithString:aString];
[scanner scanUpToString:@"@" intoString:nil];
while(![scanner isAtEnd]) {
NSString *substring = nil;
[scanner scanString:@"@" intoString:nil];
if([scanner scanUpToString:@" " intoString:&substring]) {
[substrings addObject:substring];
}
[scanner scanUpToString:@"@" intoString:nil];
}
因此,您已經正確提取了所有名稱? 如果是這樣,您似乎想要的是NSAttributedString 。 更多信息在這里 。
像這樣: [str setTextColor:[UIColor blueColor] range:NSMakeRange(0,5)];
對於粗體文本,請使用[UIFont boldSystemFontOfSize:fontSize]
。 請參閱上面第二個鏈接中的示例。
您必須通過在2種字體和顏色之間滑動來構建NSAttributedString。
如果能夠檢測到它們,則可能應該用已知的標記(例如:@aName)將它們括起來來替換您的名稱。 然后,解析該字符串以構建NSAttributedString。
您可以使用以下代碼(未經測試,您可能需要進行調整):
// String to parse
NSString *markup = @"MT <color>@OraTV</color>: SNEAK PEEK: <color>@tomgreenlive</color>...";
// Names font and color
UIFont *boldFont = [UIFont boldSystemFontOfSize:15.0f];
UIColor *boldColor = [UIColor blueColor];
// Other text font and color
UIFont *stdFont = [UIFont systemFontOfSize:15.0f];
UIColor *stdColor = [UIColor blackColor];
// Current font and color
UIFont *currentFont = stdFont;
UIColor *currentColor = stdColor;
// Parse HTML string
NSMutableAttributedString *aString = [[NSMutableAttributedString alloc] initWithString:@""];
NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:@"(.*?)(<[^>]+>|\\Z)"
options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators
error:nil];
NSArray *chunks = [regex matchesInString:markup options:0 range:NSMakeRange(0, [markup length])];
for (NSTextCheckingResult* b in chunks)
{
NSArray *parts = [[markup substringWithRange:b.range] componentsSeparatedByString:@"<"];
NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:currentFont,NSFontAttributeName,currentColor,NSForegroundColorAttributeName,nil];
[aString appendAttributedString:[[NSAttributedString alloc] initWithString:[parts objectAtIndex:0] attributes:attrs]];
if([parts count] > 1)
{
NSString *tag = (NSString *)[parts objectAtIndex:1];
if([tag hasPrefix:@"color"])
{
currentFont = boldFont;
currentColor = boldColor;
}
else if([tag hasPrefix:@"/color"])
{
currentFont = stdFont;
currentColor = stdColor;
}
}
}
希望能有所幫助。
西里爾
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.