UILabel带有两种不同颜色的文本


109

我想在中显示这样的字符串UILabel

有5个结果。

其中数字5为红色,字符串的其余部分为黑色。

如何在代码中执行此操作?


6
@EmptyStack肯定不是这种情况,因为iOS 4支持NSAttributedString。请参阅下面的答案。
Mic Pringle

Answers:


223

这样做的方法是这样使用NSAttributedString

NSMutableAttributedString *text = 
 [[NSMutableAttributedString alloc] 
   initWithAttributedString: label.attributedText];

[text addAttribute:NSForegroundColorAttributeName 
             value:[UIColor redColor] 
             range:NSMakeRange(10, 1)];
[label setAttributedText: text];

我创建了一个UILabel 扩展来做到这一点


我可以在上面添加目标吗?致谢
UserDev 2015年

我刚刚将扩展名添加到我的项目中!谢谢!
2015年

UILabel的不错类别。非常感谢。这应该是公认的答案。
Pradeep Reddy Kypa 2015年

63

我已经通过创建一个这样做categoryNSMutableAttributedString

-(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
}

SWIFT 4 @ kj13感谢您的通知

// If no text is send, then the style will be applied to full text
func setColorForText(_ textToFind: String?, with color: UIColor) {

    let range:NSRange?
    if let text = textToFind{
        range = self.mutableString.range(of: text, options: .caseInsensitive)
    }else{
        range = NSMakeRange(0, self.length)
    }
    if range!.location != NSNotFound {
        addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range!)
    }
}

我做了更多关于属性的实验,下面是结果,这是 SOURCECODE

这是结果

款式


2
您需要使用以下方法为NSMutableAttributedString创建一个新的类别...无论如何,我将此示例添加到github,您可以抓取并检查它github.com/anoop4real/NSMutableAttributedString-Color
anoop4real

但是我需要在字符串中设置所有字母的颜色,以不区分大小写....就像在整个字符串的红色中使用所有“ e”一样
Ravi Ojha

“ NSMutableAttributedString”没有可见的@interface声明选择器“ setColorForText:withColor:”
ekashking

1
我在Swift4.1中收到错误消息'使用未解决的标识符'NSForegroundColorAttributeName',但是我将'NSForegroundColorAttributeName'替换为'NSAttributedStringKey.foregroundColor'并正确构建。
kj13 '18

1
@ kj13感谢您的通知,我更新了答案并添加了更多样式
anoop4real

25

干得好

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;

20

斯威夫特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)

结果

在此处输入图片说明


迅捷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)
        }
    }

结果:

在此处输入图片说明


12
//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;

6

iOS 6开始,UIKit支持绘图属性字符串,因此无需扩展或替换。

来自UILabel

@property(nonatomic, copy) NSAttributedString *attributedText;

您只需要建立自己的NSAttributedString。基本上有两种方法:

  1. 附加具有相同属性的文本块-为每个部分创建一个NSAttributedString实例并将其附加到一个NSMutableAttributedString

  2. 从纯字符串创建属性文本,然后添加给定范围的属性–查找数字范围(或其他),并在其上应用不同的颜色属性。


6

安纳普斯迅速回答。可以从任何类重复使用。

在快速文件中

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;




3

JTAttributedLabel(由mystcolor编写)使您可以在iOS 6下的UILabel中使用属性字符串支持,并同时通过其JTAutoLabel在iOS 5下使用其JTAttributedLabel类。


2

有一个Swift 3.0解决方案

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

    }
}

还有一个call的例子:

let colorString = " (string in red)"
self.mLabel.text = "classic color" + colorString
self.mLabel.setSubTextColor(pSubString: colorString, pColor: UIColor.red)

嗨,如果要添加两个不同的colorStrings,该怎么办?我尝试使用您的例子,只需添加一个又一个,但..它仍然只是颜色其中之一
埃里克Auranaune

试试这个:let colorString =“(红色字符串)” let colorStringGreen =“(绿色字符串)” self.mLabel.text =“经典颜色” + colorString + colorStringGreen self.mLabel.setSubTextColor(pSubString:colorString,pColor:UIColor .red)self.mLabel.setSubTextColor(pSubString:colorStringGreen,pColor:UIColor.green)
Kevin ABRIOUX

这很奇怪,它仍然没有改变:s24.postimg.org/ds0rpyyut/…
Erik Auranaune

一个问题是,如果两个字符串相同,那么只会为其中一个着色,请看这里:pastebin.com/FJZJTpp3。您还为此解决了吗?
Erik Auranaune

2

Swift 4及更高版本:anoop4real解决方案的启发,这是一个String扩展,可用于生成具有2种不同颜色的文本。

extension String {

    func attributedStringForPartiallyColoredText(_ textToFind: String, with color: UIColor) -> NSMutableAttributedString {
        let mutableAttributedstring = NSMutableAttributedString(string: self)
        let range = mutableAttributedstring.mutableString.range(of: textToFind, options: .caseInsensitive)
        if range.location != NSNotFound {
            mutableAttributedstring.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
        }
        return mutableAttributedstring
    }
}

下面的示例将星号的颜色更改为红色,同时保留其余文本的原始标签颜色。

label.attributedText = "Enter username *".attributedStringForPartiallyColoredText("*", with: #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1))

2

我的答案还可以选择为所有出现的文本着色,不仅是一个文本出现:“ wa ba wa ba dubdub”,还可以像接受的答案一样,仅对所有出现的wa颜色进行着色。

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 setColorForAllOccuranceOfText(_ textToFind: String, with color: UIColor) {
        let inputLength = self.string.count
        let searchLength = textToFind.count
        var range = NSRange(location: 0, length: self.length)

        while (range.location != NSNotFound) {
            range = (self.string as NSString).range(of: textToFind, options: [], range: range)
            if (range.location != NSNotFound) {
                self.addAttribute(NSForegroundColorAttributeName, value: color, range: NSRange(location: range.location, length: searchLength))
                range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
            }
        }
    }
}

现在您可以执行以下操作:

let message = NSMutableAttributedString(string: "wa ba wa ba dubdub")
message.setColorForText(subtitle, with: UIColor.red) 
// or the below one if you want all the occurrence to be colored 
message.setColorForAllOccuranceOfText("wa", with: UIColor.red) 
// then you set this attributed string to your label :
lblMessage.attributedText = message

我该如何使用呢?
pableiros

1
更新了我的答案,
祝您

1

对于Xamarin用户,我有一个静态C#方法,我在其中传递字符串数组,UIColours数组和UIFonts数组(它们的长度需要匹配)。然后将属性字符串传回。

看到:

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;

    }

1

就我而言,我正在使用Xcode 10.1。在Interface Builder中的Label文本中,可以在纯文本和属性文本之间进行切换的选项

在此处输入图片说明

希望这可以帮助其他人..!


2
看起来XCode 11.0打破了Attributed Text编辑器。因此,我尝试使用TextEdit创建文本,然后将其粘贴到Xcode中,并且效果惊人。
Brainware

0
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

    }
}

0

我自己的解决方案创建了一种类似于下一个的方法:

-(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; }

它只能在同一文本中使用一种不同的颜色,但是您可以轻松地将其适应于同一句子中的更多颜色。


0

通过使用以下代码,您可以基于单词设置多种颜色。

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];
}

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.