【发布时间】:2016-10-14 00:18:01
【问题描述】:
我需要检查一个 NSMutableString 与我在最初是 NSString 时插入的值。
一个例子是:
NString* textToDraw = @"";
textToDraw = [textToDraw stringByAppendingString:[[NSString alloc] initWithFormat:@"
Summary of currently worked on process\n\nTitle name:\nResults for Process\n %@\n%@\n%@\n, resultOne, resultTwo, resultThree]];
resultOne、resultTwo、resultThree 只是标准的 NSString 值
然后我初始化一个 NSMutableAttributedString 以添加一些格式。
NSMutableAttributedString *summaryBody = [[NSMutableAttributedString alloc] initWithString:textToDraw];
CTFontRef centuryGothicStandard;
CTFontRef centuryGothicTitle;
centuryGothicStandard = CTFontCreateWithName(CFSTR("Century Gothic"), 12.0, nil);
centuryGothicTitle = CTFontCreateWithName(CFSTR("Century Gothic-Bold"), 24.0, nil);
//Modify the summary, so that the title is larger, and bolded, the subtitles are bolded, and the text is century gothic font
[summaryBody addAttribute:(id)kCTFontAttributeName
value:(__bridge id)centuryGothicStandard
range:NSMakeRange(0, [summaryBody length])];
我需要做的是将resultOne、resultTwo 和resultThree 修改为红色,我尝试了Change attributes of substrings in a NSAttributedString 中的答案解决方案,但我不明白这个概念。
我可以简单地遍历 NSMutableAttributedString 并找到我插入的特定字符,比如“|”作为起点和“?”为终点? 我已经搜索了一个特定的索引,但没有任何与 NSAttributedMutatableString 相关的弹出,只是 NSRange,我不会具体知道。
这里有一些伪代码来帮助解释我认为可能的解决方案:
textToDraw = [textToDraw stringByAppendingString:[[NSString alloc] initWithFormat:@" Summary of currently worked on process\n\nTitle name:\nResults for Process\n |%@?\n|%@?\n|%@?\n, resultOne, resultTwo, resultThree]];
(for int i = 0; i < [NSAttributedMutatableString length]; i++)
{
if(char at i == '|')
{
get an NSRange from this value to the char at i == '?'
[NSAttributedMutatableStringS addAttribute:(id)kCTForegroundColorAttributeName
value:(id)[UIColor redColor].CGColor
range:NSMakeRange(0, NSRangeAbove])];
}
}
我目前可以获取resultOne之类的值,并创建带有改变颜色的附加属性的NSAttributedStrings,唯一的问题当然是不知道索引值,所以这是另一种可能。
【问题讨论】:
标签: ios objective-c cocoa-touch nsattributedstring