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

时间:2016-01-15 09:47:45

标签: ios swift xcode swift2 uilabel

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

叫我懒惰,但我不想回到我的所有表单,添加许多标有星号的标签,然后重新进行自动布局以容纳新标签。

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

6 个答案:

答案 0 :(得分:9)

您可以使用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

参考:Use multiple font colors in a single label - Swift

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

答案 1 :(得分:5)

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;

答案 2 :(得分:4)

UILabel具有.attributedText类型的NSAttributedString属性。

  

<强>声明

     

@NSCopying var attributedText:NSAttributedString?

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

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

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

答案 3 :(得分:1)

Swift 4
注意:属性字符串键的表示法在swift 4 中更改)

以下是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)
    }

}

现在,使用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)

答案 4 :(得分:0)

我知道这是一个老帖子,但我想分享我的方法(这是基于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

}

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

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

希望这有助于任何人。

答案 5 :(得分:0)

func updateAttributedStringWithCharacter(title : String, uilabel: UILabel) {
    let text = title + "*"
    let range = (text as NSString).range(of: "*")
    let attributedString = NSMutableAttributedString(string:text)
    attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red , range: range)
    uilabel.attributedText = attributedString }