xcode 是否可以为 UILabel 中的一个字符设置不同的颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34808297/
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-09-15 08:26:13  来源:igfitidea点击:

Is it possible to set a different colour for one character in a UILabel?

iosswiftxcodeswift2uilabel

提问by zack_falcon

I've been working on a small project using Xcode. It uses a lot of labels, textfields, etc. I've finished with most of the layout, the constrains, and the forms, titles, etc. After which, the client announces that for all required fields, there should be a red asterisk next to the label.

我一直在使用 Xcode 开发一个小项目。它使用了很多标签、文本字段等。我已经完成了大部分布局、约束以及表单、标题等。之后,客户宣布对于所有必填字段,应该有一个红色星号标签旁边。

Call me lazy, but I'd rather not go back to all of my forms, add in a lot of labels with asterisks on them, and re-do my auto-layout to accommodate the new labels.

说我懒惰,但我不想回到我所有的表单,添加很多带有星号的标签,然后重新进行自动布局以适应新标签。

So, is there a way to change the colour of a specific character (in this case, the asterisk) in a UILabel, while the rest of the text stays black?

那么,有没有办法更改 UILabel 中特定字符(在本例中为星号)的颜色,而其余文本保持黑色?

回答by tuledev

You can use NSMutableAttributedString. You can set specific range of your string with different color, font, size, ...

您可以使用NSMutableAttributedString. 您可以使用不同的颜色、字体、大小等设置字符串的特定范围。

E.g:

例如:

 var range = NSRange(location:2,length:1) // specific location. This means "range" handle 1 character at location 2

 attributedString = NSMutableAttributedString(string: originalString, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
 // here you change the character to red color
 attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)
 label.attributedText = attributedString

Ref: Use multiple font colors in a single label - Swift

参考:在单个标签中使用多种字体颜色 - Swift

You can change a lot of attribute of String. Ref from apple: https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/index.html

您可以更改 String 的很多属性。来自苹果的参考:https: //developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/index.html

回答by Ramesh_T

let text = "Sample text *"
let range = (text as NSString).rangeOfString("*")
let attributedString = NSMutableAttributedString(string:text)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)

    //Apply to the label
    myLabel.attributedText = attributedString;

回答by dfri

UILabelhave an .attributedTextproperty of type NSAttributedString.

UILabel有一个.attributedText类型的属性NSAttributedString

Declaration

@NSCopying var attributedText: NSAttributedString?

宣言

@NSCopying 变量属性文本:NSAttributedString?

You let your asterix *have a single .redColor()attribute (NSForegroundColorAttributeName), whereas the rest of the new label simply uses the same text as before, however also contained in an NSAttributedTextString.

您让您的星号*具有单个.redColor()属性 ( NSForegroundColorAttributeName),而新标签的其余部分仅使用与以前相同的文本,但也包含在NSAttributedTextString.

An example follows below using a function to repeatedly update your existing labels to attributed strings prefixed with a red *:

下面的示例使用函数将现有标签重复更新为以 red 为前缀的属性字符串*

class ViewController: UIViewController {

    @IBOutlet weak var myFirstLabel: UILabel!
    @IBOutlet weak var mySecondLabel: UILabel!

    let myPrefixCharacter = "*"
    let myPrefixColor = UIColor.redColor()    

    // ...

    override func viewDidLoad() {
        super.viewDidLoad()

        // ...

        /* update labels to attributed strings */
        updateLabelToAttributedString(myFirstLabel)
        updateLabelToAttributedString(mySecondLabel)
        // ...

    }

    func updateLabelToAttributedString(label: UILabel) {

        /* original label text as NSAttributedString, prefixed with " " */
        let attr = [ NSForegroundColorAttributeName: myPrefixColor ]
        let myNewLabelText = NSMutableAttributedString(string: myPrefixCharacter, attributes: attr)
        let myOrigLabelText = NSAttributedString(string: " " + (label.text ?? ""))

        /* set new label text as attributed string */
        myNewLabelText.appendAttributedString(myOrigLabelText)
        label.attributedText = myNewLabelText
    }

    // ...

}

enter image description here

在此处输入图片说明

回答by Krunal

Swift 4
(Note: notation for attributed string key is changed in swift 4)

Swift 4
注意:属性字符串键的符号在 swift 4 中发生了变化

Here is an extension for NSMutableAttributedString, that add/set color on string/text.

这是 的扩展NSMutableAttributedString,在字符串/文本上添加/设置颜色。

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

}

Now, try above extension with UILabeland see result

现在,尝试上面的扩展UILabel并查看结果

let label = UILabel()
label.frame = CGRect(x: 40, y: 100, width: 280, height: 200)
let red = "red"
let blue = "blue"
let green = "green"
let stringValue = "\(red)\n\(blue)\n&\n\(green)"
label.textColor = UIColor.lightGray
label.numberOfLines = 0
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColor(color: UIColor.red, forText: red)   // or use direct value for text "red"
attributedString.setColor(color: UIColor.blue, forText: blue)   // or use direct value for text "blue"
attributedString.setColor(color: UIColor.green, forText: green)   // or use direct value for text "green"
label.font = UIFont.systemFont(ofSize: 26)
label.attributedText = attributedString
self.view.addSubview(label)

回答by Wilson Mu?oz

I know this is an old post, but i want to share my approach (which is based on the answer from dfri) i just made it a function for convenience.

我知道这是一篇旧帖子,但我想分享我的方法(基于 dfri 的答案)我只是为了方便起见将其设为一个函数。

func lastCharOnColor(label: UILabel, color: UIColor, length: Int) {

    //First we get the text.
    let string = label.text

    //Get number of characters on string and based on that get last character index.
    let characterCounter    = string?.characters.count
    let lastCharacterIndex  = characterCounter!-1

    //Set Range
    let range = NSRange(location: lastCharacterIndex, length: length)
    let attributedString = NSMutableAttributedString(string: string!, attributes: nil)

    //Set label
    attributedString.addAttribute(NSForegroundColorAttributeName, value: color, range: range)
    label.attributedText = attributedString

}

I use this function to just set the last character from a label to a certain color like this:

我使用此函数将标签中的最后一个字符设置为某种颜色,如下所示:

        lastCharOnColor(label: self.labelname, color: UIColor.red, length: 1)

Hope this helps anyone.

希望这可以帮助任何人。