UILabel与两种不同颜色的文字
我想在UILabel
显示这样的string:
有5个结果。
5号的颜色是红色的,其余的是黑色的。
我如何在代码中做到这一点?
这样做的方法是使用NSAttributedString
像这样:
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString: label.attributedText]; [text addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(10, 1)]; [label setAttributedText: text];
我创build了一个UILabel
扩展来做到这一点 。
我通过为NSMutableAttributedString
创build一个category
来完成这个工作
-(void)setColorForText:(NSString*) textToFind withColor:(UIColor*) color { NSRange range = [self.mutableString rangeOfString:textToFind options:NSCaseInsensitiveSearch]; if (range.location != NSNotFound) { [self addAttribute:NSForegroundColorAttributeName value:color range:range]; } }
像使用它
- (void) setColoredLabel { NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"Here is a red blue and green text"]; [string setColorForText:@"red" withColor:[UIColor redColor]]; [string setColorForText:@"blue" withColor:[UIColor blueColor]]; [string setColorForText:@"green" withColor:[UIColor greenColor]]; mylabel.attributedText = string; }
SWIFT 3
extension NSMutableAttributedString{ func setColorForText(_ textToFind: String, with color: UIColor) { let range = self.mutableString.range(of: textToFind, options: .caseInsensitive) if range.location != NSNotFound { addAttribute(NSForegroundColorAttributeName, value: color, range: range) } } }
用法
func setColoredLabel() { let string = NSMutableAttributedString(string: "Here is a red blue and green text") string.setColorForText("red", with: #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)) string.setColorForText("blue", with: #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)) string.setColorForText("green", with: #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)) mylabel.attributedText = string }
这是结果
干得好
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:lblTemp.text]; [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)]; [string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)]; [string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)]; lblTemp.attributedText = string;
//NSString *myString = @"I have to replace text 'Dr Andrew Murphy, John Smith' "; NSString *myString = @"Not a member?signin"; //Create mutable string from original one NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:myString]; //Fing range of the string you want to change colour //If you need to change colour in more that one place just repeat it NSRange range = [myString rangeOfString:@"signin"]; [attString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:(63/255.0) green:(163/255.0) blue:(158/255.0) alpha:1.0] range:range]; //Add it to the label - notice its not text property but it's attributeText _label.attributedText = attString;
从iOS 6开始 ,UIKit支持绘制属性string,因此不需要扩展或replace。
来自UILabel
:
@property(nonatomic, copy) NSAttributedString *attributedText;
你只需要build立你的NSAttributedString
。 基本上有两种方法:
-
附加相同属性的文本块 – 为每个部分创build一个
NSAttributedString
实例,并将它们附加到一个NSMutableAttributedString
-
从纯string创build属性文本,然后为给定范围添加属性 – find你的数字(或其他)的范围,并应用不同的颜色属性。
Anups快速回答。 可以从任何类别重用。
在swift文件中
extension NSMutableAttributedString { func setColorForStr(textToFind: String, color: UIColor) { let range = self.mutableString.rangeOfString(textToFind, options:NSStringCompareOptions.CaseInsensitiveSearch); if range.location != NSNotFound { self.addAttribute(NSForegroundColorAttributeName, value: color, range: range); } } }
在某些视图控制器中
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self.labelShopInYourNetwork.text!); attributedString.setColorForStr("YOUR NETWORK", color: UIColor(red: 0.039, green: 0.020, blue: 0.490, alpha: 1.0)); self.labelShopInYourNetwork.attributedText = attributedString;
有一个UIWebView或多个UILabel可以被视为矫枉过正这种情况。
我的build议是使用TTTAttributedLabel ,这是一个支持NSAttributedString的 UILabel的替代品。 这意味着你可以很容易地将不同的样式应用到string中的不同范围。
为了显示不需要编辑的简短格式文本, 核心文本是要走的路。 有几个使用NSAttributedString
和Core Text进行渲染的开源项目。 例如,请参阅CoreTextAttributedLabel或OHAttributedLabel 。
JTAttributedLabel (by mystcolor)允许您在iOS 6下使用UILabel中的属性string支持,同时通过其JTAutoLabel在iOS 5下使用JTAttributedLabel类。
斯威夫特4
// An attributed string extension to achieve colors on text. extension NSMutableAttributedString { func setColor(color: UIColor, forText stringValue: String) { let range: NSRange = self.mutableString.range(of: stringValue, options: .caseInsensitive) self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range) } } // Try it with label let label = UILabel() label.frame = CGRect(x: 70, y: 100, width: 260, height: 30) let stringValue = "There are 5 results." let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue) attributedString.setColor(color: UIColor.red, forText: "5") label.font = UIFont.systemFont(ofSize: 26) label.attributedText = attributedString self.view.addSubview(label)
结果
Swift 3
func setColoredLabel() { var string: NSMutableAttributedString = NSMutableAttributedString(string: "redgreenblue") string.setColor(color: UIColor.redColor(), forText: "red") string.setColor(color: UIColor.greenColor(), forText: "green") string.setColor(color: UIColor.blueColor(, forText: "blue") mylabel.attributedText = string } func setColor(color: UIColor, forText stringValue: String) { var range: NSRange = self.mutableString.rangeOfString(stringValue, options: NSCaseInsensitiveSearch) if range != nil { self.addAttribute(NSForegroundColorAttributeName, value: color, range: range) } }
结果:
NSAttributedString
是要走的路。 下面的问题有一个很好的答案,告诉你如何做到这一点你如何使用NSAttributedString
有一个Swift 3.0解决scheme
extension UILabel{ func setSubTextColor(pSubString : String, pColor : UIColor){ let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self.text!); let range = attributedString.mutableString.range(of: pSubString, options:NSString.CompareOptions.caseInsensitive) if range.location != NSNotFound { attributedString.addAttribute(NSForegroundColorAttributeName, value: pColor, range: range); } self.attributedText = attributedString } }
有一个例子叫:
let colorString = " (string in red)" self.mLabel.text = "classic color" + colorString self.mLabel.setSubTextColor(pSubString: colorString, pColor: UIColor.red)
extension UILabel{ func setSubTextColor(pSubString : String, pColor : UIColor){ let attributedString: NSMutableAttributedString = self.attributedText != nil ? NSMutableAttributedString(attributedString: self.attributedText!) : NSMutableAttributedString(string: self.text!); let range = attributedString.mutableString.range(of: pSubString, options:NSString.CompareOptions.caseInsensitive) if range.location != NSNotFound { attributedString.addAttribute(NSForegroundColorAttributeName, value: pColor, range: range); } self.attributedText = attributedString } }
我自己的解决scheme是创build一个像下一个方法:
-(void)setColorForText:(NSString*) textToFind originalText:(NSString *)originalString withColor:(UIColor*)color andLabel:(UILabel *)label{ NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:originalString]; NSRange range = [originalString rangeOfString:textToFind]; [attString addAttribute:NSForegroundColorAttributeName value:color range:range]; label.attributedText = attString; if (range.location != NSNotFound) { [attString addAttribute:NSForegroundColorAttributeName value:color range:range]; } label.attributedText = attString; }
它在同一个文本中只用了一种不同的颜色,但是你可以很容易地在同一个句子中使用更多的颜色。
对于Xamarin用户,我有一个静态的C#方法,在这里我传入一个string数组,UIColours数组和UIFonts数组(他们将需要长度匹配)。 归因的string然后传回。
看到:
public static NSMutableAttributedString GetFormattedText(string[] texts, UIColor[] colors, UIFont[] fonts) { NSMutableAttributedString attrString = new NSMutableAttributedString(string.Join("", texts)); int position = 0; for (int i = 0; i < texts.Length; i++) { attrString.AddAttribute(new NSString("NSForegroundColorAttributeName"), colors[i], new NSRange(position, texts[i].Length)); var fontAttribute = new UIStringAttributes { Font = fonts[i] }; attrString.AddAttributes(fontAttribute, new NSRange(position, texts[i].Length)); position += texts[i].Length; } return attrString; }
通过使用下面的代码,你可以设置基于单词的多种颜色。
NSMutableArray * array = [[NSMutableArray alloc] initWithObjects:@"1 ball",@"2 ball",@"3 ball",@"4 ball", nil]; NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] init]; for (NSString * str in array) { NSMutableAttributedString * textstr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ ,",str] attributes:@{NSForegroundColorAttributeName :[self getRandomColor]}]; [attStr appendAttributedString:textstr]; } UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(10, 300, 300, 30)]; lab.attributedText = attStr; [self.view addSubview:lab]; -(UIColor *) getRandomColor { CGFloat redcolor = arc4random() % 255 / 255.0; CGFloat greencolor = arc4random() % 255 / 255.0; CGFloat bluencolor = arc4random() % 255 / 255.0; return [UIColor colorWithRed:redcolor green:greencolor blue:bluencolor alpha:1.0]; }