Nub*_*lon 3 uitableview nsattributedstring ios
我有一个UITableViewCell由两个单词组成的文本标签.
如何更改单词的颜色; 将第一个单词设为绿色,将第二个单词设为红色?
ces*_*fry 10
NSString *twoWords = @"Green Red";
NSArray *components = [twoWords componentsSeparatedByString:@" "];
NSRange greenRange = [twoWords rangeOfString:[components objectAtIndex:0]];
NSRange redRange = [twoWords rangeOfString:[components objectAtIndex:1]];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:twoWords];
[attrString beginEditing];
[attrString addAttribute: NSForegroundColorAttributeName
value:[UIColor greenColor]
range:greenRange];
[attrString addAttribute: NSForegroundColorAttributeName
value:[UIColor redColor]
range:greenRange];
[attrString endEditing];
Run Code Online (Sandbox Code Playgroud)
然后你可以直接在UILabel上使用attrString(> iOS 6,查看Apple文档).
最简单的方法是在iOS 6.0或更高版本中使用nsattributedstring.你可以分配其中一个和titleLabel(或任何其他保存文本的对象)UITableViewCell.如果你正在使用,titleLabel你会这样做:
[cell.titleLabel setAttributedText:yourAttributedString];
Run Code Online (Sandbox Code Playgroud)
要使用a设置颜色NSAttributedString,请执行以下操作:
NSMutableAttributedString* attributedString = [[NSMutableAttributedString alloc] initWithString:stringToManipulate];
[attributedString beginEditing];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(0, widthOfFisrtWord)];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(widthOfFisrtWord, widthOfSecondWord)];
[attributedString endEditing];
Run Code Online (Sandbox Code Playgroud)
请注意,上面提供的范围NSMakeRange不是您需要的范围.您必须根据自己的需要更改范围,具体取决于两个单词之间是否有空格或其他字符.
Apple文档:
| 归档时间: |
|
| 查看次数: |
4278 次 |
| 最近记录: |