Используйте несколько цветов шрифта на одной этикетке

Есть ли способ использовать два или даже три цвета шрифта в одной метке в iOS?

Если бы текст «привет, как дела» использовался в качестве примера, «привет» был бы синим, а «как дела» - зеленым?

Возможно ли это, это кажется проще, чем создание нескольких ярлыков?


person Justin Rose    schedule 01.01.2015    source источник
comment
Попробуйте использовать свойство текста с атрибутами UILabel. stackoverflow.com/ questions / 3586871 /   -  person rakeshbs    schedule 01.01.2015
comment
Вы хотите добавить цвет диапазона в строку   -  person Kirit Modi    schedule 01.01.2015


Ответы (17)


Ссылка отсюда .

Прежде всего инициализируйте NSString и NSMutableAttributedString, как показано ниже.

var myString:NSString = "I AM KIRIT MODI"
var myMutableString = NSMutableAttributedString()

В ViewDidLoad

override func viewDidLoad() {

    myMutableString = NSMutableAttributedString(string: myString, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
    myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))
    // set label Attribute
    labName.attributedText = myMutableString
    super.viewDidLoad()
}

ВЫХОД

введите описание изображения здесь

НЕСКОЛЬКО ЦВЕТОВ

Добавьте приведенный ниже код строки в свой ViewDidLoad, чтобы получить несколько цветов в строке.

 myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange(location:10,length:5))

Многоцветный ВЫХОД

введите описание изображения здесь

Swift 4

var myMutableString = NSMutableAttributedString(string: str, attributes: [NSAttributedStringKey.font :UIFont(name: "Georgia", size: 18.0)!])
myMutableString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location:2,length:4))

Swift 5.0

 var myMutableString = NSMutableAttributedString(string: str, attributes: [NSAttributedString.Key.font :UIFont(name: "Georgia", size: 18.0)!])
 myMutableString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: NSRange(location:2,length:4))
person Kirit Modi    schedule 01.01.2015
comment
Можете ли вы добавить два свойства диапазона, если нет, как мне это обойти? - person Justin Rose; 01.01.2015
comment
Спасибо за Ваш ответ. В моем случае я получаю последовательно имена двух пользователей из API. Я хочу раскрасить второе имя, поэтому не знаю длины предложения. Есть ли какое-то решение для этого случая? Большое спасибо. - person Shittel; 17.04.2021

Для @Hems Moradiya

введите описание изображения здесь

let attrs1 = [NSFontAttributeName : UIFont.boldSystemFontOfSize(18), NSForegroundColorAttributeName : UIColor.greenColor()]

let attrs2 = [NSFontAttributeName : UIFont.boldSystemFontOfSize(18), NSForegroundColorAttributeName : UIColor.whiteColor()]

let attributedString1 = NSMutableAttributedString(string:"Drive", attributes:attrs1)

let attributedString2 = NSMutableAttributedString(string:"safe", attributes:attrs2)

attributedString1.appendAttributedString(attributedString2)
self.lblText.attributedText = attributedString1

Swift 4

    let attrs1 = [NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18), NSAttributedStringKey.foregroundColor : UIColor.green]

    let attrs2 = [NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18), NSAttributedStringKey.foregroundColor : UIColor.white]

    let attributedString1 = NSMutableAttributedString(string:"Drive", attributes:attrs1)

    let attributedString2 = NSMutableAttributedString(string:"safe", attributes:attrs2)

    attributedString1.append(attributedString2)
    self.lblText.attributedText = attributedString1

Swift 5

    let attrs1 = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 18), NSAttributedString.Key.foregroundColor : UIColor.green]

    let attrs2 = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 18), NSAttributedString.Key.foregroundColor : UIColor.white]

    let attributedString1 = NSMutableAttributedString(string:"Drive", attributes:attrs1)

    let attributedString2 = NSMutableAttributedString(string:"safe", attributes:attrs2)

    attributedString1.append(attributedString2)
    self.lblText.attributedText = attributedString1
person Keyur Hirani    schedule 29.09.2016

Swift 4

Используя следующую функцию расширения, вы можете напрямую установить атрибут цвета для атрибутированной строки и применить его к своей этикетке.

extension NSMutableAttributedString {

    func setColorForText(textForAttribute: String, withColor color: UIColor) {
        let range: NSRange = self.mutableString.range(of: textForAttribute, options: .caseInsensitive)

        // Swift 4.2 and above
        self.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)

        // Swift 4.1 and below
        self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
    }

}

Попробуйте расширение, указанное выше, используя метку:

let label = UILabel()
label.frame = CGRect(x: 60, y: 100, width: 260, height: 50)
let stringValue = "stackoverflow"

let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColorForText(textForAttribute: "stack", withColor: UIColor.black)
attributedString.setColorForText(textForAttribute: "over", withColor: UIColor.orange)
attributedString.setColorForText(textForAttribute: "flow", withColor: UIColor.red)
label.font = UIFont.boldSystemFont(ofSize: 40)

label.attributedText = attributedString
self.view.addSubview(label)

Результат:

введите описание изображения здесь

person Krunal    schedule 17.10.2017
comment
@Krunal Как это можно изменить для поддержки нескольких строк для изменения цвета ...? У меня длинная строка с нижними заголовками, имеющими ------------, но приведенный выше код работает нормально, но окрашивает только первый найденный. Можно ли изменить это так, чтобы все --------- строки имели определенный цвет ....? Спасибо. - person Omid CompSCI; 16.12.2018
comment
это не сработает для такого текста: flowstackoverflow он изменит только первый поток, но нам нужен последний, как этого добиться? - person swift2geek; 17.01.2020

Обновленный ответ для Swift 4

Вы можете легко использовать html внутри свойства attributedText UILabel, чтобы легко выполнять различное форматирование текста.

 let htmlString = "<font color=\"red\">This is  </font> <font color=\"blue\"> some text!</font>"

    let encodedData = htmlString.data(using: String.Encoding.utf8)!
    let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
    do {
        let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
        label.attributedText = attributedString

    } catch _ {
        print("Cannot create attributed String")
    }

введите описание изображения здесь

Обновленный ответ для Swift 2

let htmlString = "<font color=\"red\">This is  </font> <font color=\"blue\"> some text!</font>"

let encodedData = htmlString.dataUsingEncoding(NSUTF8StringEncoding)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
    let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
    label.attributedText = attributedString

} catch _ {
    print("Cannot create attributed String")
}
person rakeshbs    schedule 01.01.2015
comment
Я получил это сообщение об ошибке: Невозможно вызвать инициализатор для типа 'NSAttributedString' со списком аргументов типа '(данные: NSData, параметры: [String: String], documentAttributes: _, error: _)' - person Qian Chen; 07.12.2015
comment
в Swift 2 есть изменения. Пожалуйста, проверьте мой обновленный ответ. - person rakeshbs; 08.12.2015

Вот решение для Swift 5

let label = UILabel()
let text = NSMutableAttributedString()
text.append(NSAttributedString(string: "stack", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]));
text.append(NSAttributedString(string: "overflow", attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray]))
label.attributedText = text

введите описание изображения здесь

person Paul Wasilewski    schedule 05.10.2019

Мне так понравилось

let yourAttributes = [NSAttributedString.Key.foregroundColor: UIColor.black, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15)]
    let yourOtherAttributes = [NSAttributedString.Key.foregroundColor: UIColor.red, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 25)]

    let partOne = NSMutableAttributedString(string: "This is an example ", attributes: yourAttributes)
    let partTwo = NSMutableAttributedString(string: "for the combination of Attributed String!", attributes: yourOtherAttributes)

    let combination = NSMutableAttributedString()

    combination.append(partOne)
    combination.append(partTwo) 
person jithin    schedule 10.10.2016
comment
Спасибо за этот простой. - person Nikhil Manapure; 17.11.2017

Использовал ответ rakeshbs для создания расширения в Swift 2:

// StringExtension.swift
import UIKit
import Foundation

extension String {

    var attributedStringFromHtml: NSAttributedString? {
        do {
            return try NSAttributedString(data: self.dataUsingEncoding(NSUTF8StringEncoding)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
        } catch _ {
            print("Cannot create attributed String")
        }
        return nil
    }
}

Использование:

let htmlString = "<font color=\"red\">This is  </font> <font color=\"blue\"> some text!</font>"
label.attributedText = htmlString.attributedStringFromHtml

Или даже для однострочных

label.attributedText = "<font color=\"red\">This is  </font> <font color=\"blue\"> some text!</font>".attributedStringFromHtml

Преимущество расширения в том, что у вас будет атрибут .attributedStringFromHtml для всех String во всем приложении.

person mathielo    schedule 11.12.2015

ОБНОВЛЕНИЕ для SWIFT 5

func setDiffColor(color: UIColor, range: NSRange) {
     let attText = NSMutableAttributedString(string: self.text!)
     attText.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
     attributedText = attText
}

SWIFT 3

В своем коде я создаю расширение

import UIKit
import Foundation

extension UILabel {
    func setDifferentColor(string: String, location: Int, length: Int){

        let attText = NSMutableAttributedString(string: string)
        attText.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueApp, range: NSRange(location:location,length:length))
        attributedText = attText

    }
}

и это для использования

override func viewDidLoad() {
        super.viewDidLoad()

        titleLabel.setDifferentColor(string: titleLabel.text!, location: 5, length: 4)

    }
person Ridho Octanio    schedule 13.10.2017

Используйте NSMutableAttributedString

myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))

введите описание изображения здесь

Подробнее см. Здесь swift-using-attributed- строки

person Shamsudheen TK    schedule 01.01.2015

Swift 3.0

let myMutableString = NSMutableAttributedString(
                            string: "your desired text",
                            attributes: [:])

myMutableString.addAttribute(
                            NSForegroundColorAttributeName,
                            value: UIColor.blue,
                            range: NSRange(
                                location:6,
                                length:7))

результат:

Чтобы получить больше цветов, вы можете просто добавлять атрибуты к изменяемой строке. Дополнительные примеры см. здесь.

person Cilvet    schedule 21.02.2017

Если вы хотите использовать это много раз в своем приложении, вы можете просто создать расширение UILabel, и это упростит: -

Swift 5

extension UILabel {
    func setSpannedColor (fullText : String , changeText : String ) {
        let strNumber: NSString = fullText as NSString
        let range = (strNumber).range(of: changeText)
        let attribute = NSMutableAttributedString.init(string: fullText)
        attribute.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red , range: range)
        self.attributedText = attribute
    }
}

Используйте свой ярлык: -

yourLabel = "Hello Test"
yourLabel.setSpannedColor(fullText: totalLabel.text!, changeText: "Test")
person Paresh Mangukiya    schedule 09.12.2020

Расширение Swift 4 UILabel

В моем случае мне нужно было часто устанавливать разные цвета / шрифты в ярлыках, поэтому я сделал расширение UILabel, используя Krunal Расширение NSMutableAttributedString.

func highlightWords(phrases: [String], withColor: UIColor?, withFont: UIFont?) {

    let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self.text!)

    for phrase in phrases {

        if withColor != nil {
            attributedString.setColorForText(textForAttribute: phrase, withColor: withColor!)
        }
        if withFont != nil {
            attributedString.setFontForText(textForAttribute: phrase, withFont: withFont!)
        }

    }

    self.attributedText = attributedString

}

Его можно использовать так:

yourLabel.highlightWords(phrases: ["hello"], withColor: UIColor.blue, withFont: nil)
yourLabel.highlightWords(phrases: ["how are you"], withColor: UIColor.green, withFont: nil)
person Pablo Garces    schedule 04.12.2018

Используйте cocoapod Prestyler:

Prestyle.defineRule("*", Color.blue)
Prestyle.defineRule("_", Color.red)
label.attributedText = "*This text is blue*, _but this one is red_".prestyled()
person Kruiller    schedule 04.03.2019

Пример Swift 3 с использованием HTML-версии.

let encodedData = htmlString.data(using: String.Encoding.utf8)!
            let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
            do {
                let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
                label.attributedText = attributedString
            } catch _ {
                print("Cannot create attributed String")
            }
person spogebob92    schedule 03.01.2017

Вот код, который поддерживает последнюю версию Swift по состоянию на март 2017 года.

Swift 3.0

Здесь я создал вспомогательный класс и метод для

public class Helper {

static func GetAttributedText(inputText:String, location:Int,length:Int) -> NSMutableAttributedString {
        let attributedText = NSMutableAttributedString(string: inputText, attributes: [NSFontAttributeName:UIFont(name: "Merriweather", size: 15.0)!])
        attributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 0.401107, green: 0.352791, blue: 0.503067, alpha: 1.0) , range: NSRange(location:location,length:length))
       return attributedText
    }
}

В параметрах метода inputText: String - ваш текст, который будет отображаться в расположении метки: Int - где стиль должен быть приложением, «0» в качестве начала строки или некоторое допустимое значение в качестве позиции символа длины строки: Int - From местоположение, до скольких символов применим этот стиль.

Потребление другим способом:

self.dateLabel?.attributedText = Helper.GetAttributedText(inputText: "Date : " + (self.myModel?.eventDate)!, location:0, length: 6)

Выход:

введите здесь описание изображения

Примечание. Цвет пользовательского интерфейса может быть определен как цвет UIColor.red или определяемый пользователем цвет как UIColor(red: 0.401107, green: 0.352791, blue: 0.503067, alpha: 1.0).

person BHUVANESH MOHANKUMAR    schedule 20.03.2017

для использования этого NSForegroundColorAttributeName в быстрой более низкой версии вы можете получить неразрешенные проблемы с идентификатором, изменив указанное выше на NSAttributedStringKey.foregroundColor.

             swift lower version                swift latest version

то есть NSForegroundColorAttributeName == NSAttributedStringKey.foregroundColor

person Veerendra    schedule 25.08.2018

Swift 4.2

    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = NSTextAlignment.center

    var stringAlert = self.phoneNumber + "로\r로전송인증번호를입력해주세요"
    let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringAlert, attributes: [NSAttributedString.Key.paragraphStyle:paragraphStyle,  .font: UIFont(name: "NotoSansCJKkr-Regular", size: 14.0)])
    attributedString.setColorForText(textForAttribute: self.phoneNumber, withColor: UIColor.init(red: 1.0/255.0, green: 205/255.0, blue: 166/255.0, alpha: 1) )
    attributedString.setColorForText(textForAttribute: "로\r로전송인증번호를입력해주세요", withColor: UIColor.black)

    self.txtLabelText.attributedText = attributedString

Результат

 Результат

person Tung Tran    schedule 19.03.2019