我有一個如圖所示的顯示幕

我從一個字串 str 得到這個,如下所示

我試過的代碼
lbl1.text=newStr;
NSString *textxtra = @"Xtra";
NSString *textremove = @"Remove";
NSMutableAttributedString *attrsString = [[NSMutableAttributedString alloc] initWithAttributedString:lbl1.attributedText];
// search for word occurrence
NSRange range = [lbl1.text rangeOfString:textxtra];
NSRange range1 = [lbl1.text rangeOfString:textremove];
if (range.location != NSNotFound) {
[attrsString addAttribute:NSForegroundColorAttributeName value:[UIColor systemGreenColor] range:range];
}
if (range1.location != NSNotFound) {
[attrsString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range1];
}
// set attributed text
lbl1.attributedText = attrsString;
如何在 Xtra (American Cheese) 之前和 Xtra($1) 之后以綠色獲取字串?
Remove(House Mayo)之前的部分是紅色的?即整個字串American Cheese: Xtra $1應該在green color. 我的想法是在 Xtra upto \n 之前的 \nie 字串和 Xtra upto \n 之后的字串之間取字串,但無法準確理解如何實作
任何想法/建議都會有所幫助
uj5u.com熱心網友回復:
未經測驗,但這應該可以解決問題:
NSString *initialSting = @"";
NSArray *lines = [initialSting componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSMutableArray *attributedLines = [[NSMutableArray alloc] init];
NSDictionary *redAttributes = @{};
NSDictionary *greenAttributes = @{};
for (NSString *aLine in lines)
{
NSAttributedString *aLineAttributedString;
//Here, you could also check, that the string is like "someString: Xtra someOtherString", because if Xtra is misplaced...
if ([aLine containsString:@"Xtra"])
{
aLineAttributedString = [[NSAttributedString alloc] initWithString:aLine attributes:greenAttributes];
//Here, you could also check, that the string is like "someString: Remove someOtherString", because if Remove is misplaced...
}
else if ([aLine containsString:@"Remove"])
{
aLineAttributedString = [[NSAttributedString alloc] initWithString:aLine attributes:redAttributes];
}
else
{
aLineAttributedString = [[NSAttributedString alloc] initWithString:aLine];
}
[attributedLines addObject:aLineAttributedString];
}
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
NSAttributedString *newLine = [[NSAttributedString alloc] initWithString:@"\n"];
if ([attributedLines count] > 0)
{
for (NSUInteger i = 0; i < [attributedLines count] - 1; i )
{
[attributedString appendAttributedString:attributedLines[i]];
[attributedString appendAttributedString:newLine];
}
[attributedString appendAttributedString:[attributedLines lastObject]];
}
邏輯:使用
Create an array of
為每一行獲取一個 NSString陣列,該陣列將為每一行填充。
對于每一行,如果需要,為它著色,然后將其添加到陣列中。
最后,沒有for ,所以做一個手動 for 回圈來重建 final 。componentsSeparatedByCharactersInSet:NSAttributedStringcomponentsJoinedByString:NSAttributedStringNSAttributedString
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/467278.html
標籤:IOS 目标-c nsattributedstring
上一篇:System.Runtime.InteropServices.InvalidComObjectException:嘗試使用Microsoft.Office.Interop.Excel寫入Excel單元
下一篇:將列合并為二維串列中的一個字串
