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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6501808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 20:32:52  来源:igfitidea点击:

UILabel with text of two different colors

iosobjective-cswiftuilabeltextcolor

提问by Peter

I want to display a string like this in a UILabel:

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

There are 5 results.

有 5 个结果。

Where the number 5 is red in color and the rest of the string is black.

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

How can I do this in code?

我怎样才能在代码中做到这一点?

回答by Jo?o Costa

The way to do it is to use NSAttributedStringlike this:

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

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

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

I created a UILabelextension to do it.

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

回答by anoop4real

I have done this by creating a categoryfor NSMutableAttributedString

我已经通过创建一个categoryforNSMutableAttributedString

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

Use it like

使用它就像

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

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

USAGE

用法

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 Thanks for notifying

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!)
    }
}

I have did more experiments with attributes and below are the results, here is theSOURCECODE

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

Here is the result

这是结果

Styles

样式

回答by Hardik Mamtora

Here you go

干得好

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;

回答by Krunal

Swift 4

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

Result

结果

enter image description here

在此处输入图片说明


Swift 3


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

Result:

结果:

enter image description here

在此处输入图片说明

回答by raju dontiboina

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

回答by Deepak Thakur

Anups answer in swift. Can be reused from any class.

Anups 迅速回答。可以从任何类中重用。

In swift file

在快速文件中

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

    }
}

In Some view controller

在一些视图控制器中

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;

回答by Tricertops

Since iOS 6, UIKit supports drawing attributed strings, so no extension or replacement is needed.

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

From UILabel:

来自UILabel

@property(nonatomic, copy) NSAttributedString *attributedText;

You just need to build up your NSAttributedString. There are basically two ways:

你只需要建立你的NSAttributedString. 基本上有两种方式:

  1. Append chunks of text with the same attributes - for each part create one NSAttributedStringinstance and append them to one NSMutableAttributedString

  2. Create attributed text from plain string and then add attributed for given ranges – find the range of your number (or whatever) and apply different color attribute on that.

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

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

回答by Mic Pringle

Having a UIWebView or more than one UILabel could be considered overkill for this situation.

在这种情况下,拥有一个 UIWebView 或多个 UILabel 可能被认为是矫枉过正。

My suggestion would be to use TTTAttributedLabelwhich is a drop-in replacement for UILabel that supports NSAttributedString. This means you can very easily apply differents styles to different ranges in a string.

我的建议是使用TTTAttributedLabel,它是支持NSAttributedString 的UILabel 的替代品。这意味着您可以非常轻松地将不同的样式应用于字符串中的不同范围。

回答by omz

For displaying short, formatted text that doesn't need to be editable, Core Textis the way to go. There are several open-source projects for labels that use NSAttributedStringand Core Text for rendering. See CoreTextAttributedLabelor OHAttributedLabelfor example.

为了显示不需要可编辑的简短格式化文本,Core Text是要走的路。有几个开源项目使用标签NSAttributedString和 Core Text 进行渲染。例如,请参阅CoreTextAttributedLabelOHAttributedLabel

回答by werner

NSAttributedStringis the way to go. The following question has a great answer that shows you how to do it How do you use NSAttributedString

NSAttributedString是要走的路。以下问题有一个很好的答案,向您展示了如何使用 NSAttributedString