按顺序显示编辑的 NSString [英] Display edited NSString in order
问题描述
在这个伟大社区的帮助下,我已经为此工作了几天.
I have been working on this for a few days with help from this great community.
我有一个 NSArray
,我需要在其中编辑 NSStrings
.我已经设法检测到字符串中的标记并将其设为粗体.但是现在我试图按照它们在 NSArray 中的顺序显示字符串,同时保持添加到特定字符串的粗体.
I have a NSArray
that I need to edit NSStrings
within. I have managed to detect a marker in the string and make it bold. However now I am trying to display the strings in the order that they are within the NSArray whilst maintaining the Bold that was added to the specific strings.
我可以显示单个粗体字符串 'string
' 但我需要它,以便它在数组中.我知道 stringByAppendingString
但这会把它放在最后.
I can display the individual Bold String 'string
' but I need it to be in order that it is within the array. I know of stringByAppendingString
but this would put it at the end.
任何方向都会很棒.
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"];
编辑
根据下面的答案,我得到了它的工作,但是大胆的方法调用了这个错误:
Based on the answers below I got it working however the bold method invokes this error:
推荐答案
只需使用额外的数组.将您的代码更改为
Just use additional array. Change your code to
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 在调试窗口中显示属性字符串的一种方式:
Your additional issue is not a error - this is a way how XCode shows attributed strings in debug window:
这篇关于按顺序显示编辑的 NSString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!