在这个很棒的社区的帮助下,我已经为此工作了几天。
我有一个NSArray
,我需要在其中编辑NSStrings
。我设法检测到字符串中的标记并将其加粗。但是,现在我尝试按字符串在NSArray中的顺序显示它们,同时保持添加到特定字符串的粗体。
我可以显示单个粗体字符串'string
',但我需要将其显示在数组中。我知道stringByAppendingString
,但这会放在结尾。
任何方向都将是辉煌的。
for (NSString *testWord in legislationArray) {
if ([testWord rangeOfString:@"BOLDME"].location != NSNotFound) {
//Remove Marker
NSString *stripped = [testWord stringByReplacingOccurrencesOfString:@"BOLDME" withString:@""];
//Get string and add bold
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:stripped];
NSRange selectedRange = [stripped rangeOfString:(stripped)];
[string beginEditing];
[string addAttribute:NSFontAttributeName
value:[UIFont fontWithName:@"Helvetica-Bold" size:18.0]
range:selectedRange];
[string endEditing];
//Where to go now with string?
}
}
cell.dynamicLabel.text = [legislationArray componentsJoinedByString:@"\n"];
编辑
根据下面的答案,我可以正常工作,但是粗体方法会调用此错误:
最佳答案
只需使用其他数组即可。将您的代码更改为
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] init];
for (NSString *testWord in legislationArray) {
if ([testWord rangeOfString:@"BOLDME"].location != NSNotFound) {
//Remove Marker
NSString *stripped = [testWord stringByReplacingOccurrencesOfString:@"BOLDME" withString:@""];
//Get string and add bold
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:stripped];
NSRange selectedRange = [stripped rangeOfString:(stripped)];
[string beginEditing];
[string addAttribute:NSFontAttributeName
value:[UIFont fontWithName:@"Helvetica-Bold" size:18.0]
range:selectedRange];
[string endEditing];
//Where to go now with string?
[attrString appendAttributedString:string];
}
else
{
[attrString appendAttributedString:[[NSAttributedString alloc] initWithString:testWord]];
}
// NEW LINE
[attrString appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n"]];
}
cell.dynamicLabel.attributedText = attrString;
更新:
您的其他问题不是错误-这是XCode在调试窗口中显示属性字符串的一种方式:
关于ios - 按顺序显示编辑的NSString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23469509/