Search code examples
iosswiftxcodeuicolornsmutableattributedstring

Adding color to a word in string using NSMutableAttributedString


I am trying to add color to 2 words in a string. This is the code I am using:

        var HighScore:Int = 0
        var CurrentScore:Int = 0

        let stringOne = "You have managed to score \(CurrentScore). Current record is \(self.HighScore). Play again and give it another try!"
        let stringTwo = "\(CurrentScore)"
        let stringThree = "\(HighScore)"

        let range1 = (stringOne as NSString).range(of: stringTwo)
        let range2 = (stringOne as NSString).range(of: stringThree)

        let attributedText = NSMutableAttributedString.init(string: stringOne)

        attributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor.init(netHex: 0x00b4ff) , range: range1)
        attributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor.init(netHex: 0x00b4ff) , range: range2)

        gameOverDescriptionLabel.attributedText = attributedText

The problem I have is that if CurrentScore and HighScore is the same(ex: 2 & 2) the color on the range2 still stays white, but if they are not equal(2 & 1 or 1 & 2) both gets the color I have choosen.

Any suggestions?


Solution

  • Add this to the top or bottom of your .swift file:

    extension NSMutableAttributedString {
        func bold(_ text:String) -> NSMutableAttributedString {
            let attrs:[String:AnyObject] = [NSForegroundColorAttributeName: UIColor.init(netHex: 0x00b4ff)]
            let boldString = NSMutableAttributedString(string:"\(text)", attributes:attrs)
            self.append(boldString)
            return self
        }
    
        func normal(_ text:String)->NSMutableAttributedString {
            let normal =  NSAttributedString(string: text)
            self.append(normal)
            return self
        }
    }
    

    To code below is the usage, you can edit it how you'd like, but I have made it so you can easy just copy&paste it to your project:

                let formattedString = NSMutableAttributedString()
                formattedString
                    .normal("You have managed to score ")
                    .bold("\(CurrentScore)")
                    .normal(". Current record is ")
                    .bold("\(HighScore)")
                    .normal(". Play again and give it another try!")
    
                gameOverDescriptionLabel.attributedText = formattedString