Iphone 将特定的字符串模式设为粗体和蓝色
我有一个程序,我从twitter上获取推文,并在UITableviewcell中显示它们。现在的问题是,我必须把所有的推特名字都改成粗体和蓝色,并在原始推特上用粗体和蓝色的名字显示出来。 例如,我有这样的推特 MT@OraTV:skeek PEEK:@tomgreenlive@TheoVon&@DavidBegnaud talk麦莉的短毛蝙蝠&更多信息 所以所有以@开头的名字都应该是粗体和蓝色的 我使用这段代码提取所有以@开头的名称,但不知道如何加粗和显示 将它们放在单个uitableviewcell中Iphone 将特定的字符串模式设为粗体和蓝色,iphone,ios,objective-c,twitter,nsattributedstring,Iphone,Ios,Objective C,Twitter,Nsattributedstring,我有一个程序,我从twitter上获取推文,并在UITableviewcell中显示它们。现在的问题是,我必须把所有的推特名字都改成粗体和蓝色,并在原始推特上用粗体和蓝色的名字显示出来。 例如,我有这样的推特 MT@OraTV:skeek PEEK:@tomgreenlive@TheoVon&@DavidBegnaud talk麦莉的短毛蝙蝠&更多信息 所以所有以@开头的名字都应该是粗体和蓝色的 我使用这段代码提取所有以@开头的名称,但不知道如何加粗和显示 将它们放在单个uitableviewc
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];
}
你已经把所有的名字都提取出来了?如果是这样的话,这似乎就是你想要的。更多信息 类似这样的内容:[str setTextColor:[UIColor blueColor]range:NSMakeRange0,5];
对于粗体文本,请使用[UIFont boldSystemFontOfSize:fontSize]。请参见上面第二个链接中的示例。您必须通过在两种字体和颜色之间切换来构建NSAttributed字符串 如果你能检测到它们,你可能应该用一个已知的标记来替换你的名字,例如:@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;
}
}
}
希望有帮助
西里尔