2015-01-01 4 views
59

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

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

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

+0

Попробуйте использовать приписываемое текст свойства UILabel. http://stackoverflow.com/questions/3586871/bold-non-bold-text-in-a-single-uilabel – rakeshbs

+0

Вы хотите добавить цвет диапазона в строку –

ответ

101

Для получения дополнительной информации, see my blog post.

Прежде всего инициализировать вас 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() 
} 

** Ваш ВЫВОД: **

enter image description here

многоцветность

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

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

Рассеянный цвет ВЫВОД

enter image description here

+0

можете ли вы добавить два свойства диапазона, если нет, как мне обойти это? –

5

Воспользоваться NSMutableAttributedString

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

enter image description here

Смотреть подробнее здесь swift-using-attributed-strings

17

Обновленный ответ для 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") 
    } 

enter image description here

Обновлено Ответ на 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") 
} 
+2

Я получил это сообщение об ошибке: не удается вызвать инициализатор для типа 'NSAttributedString' с аргументом list type (данные: NSData, options: [String: String], documentAttributes: _, error: _) ' –

+2

есть изменения в Swift 2. Пожалуйста, проверьте мой обновленный ответ. – rakeshbs

6

Используется rakeshbs «s ответ создать расширение в 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 с на протяжении всего вашего приложения.

18

Для @Hems Moradiya

enter image description here

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 
3

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

let yourAttributes = [NSForegroundColorAttributeName: UIColor.black, NSFontAttributeName: UIFont.systemFontOfSize(15)] 
let yourOtherAttributes = [NSForegroundColorAttributeName: UIColor.red, NSFontAttributeName: UIFont.systemFontOfSize(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.appendAttributedString(partOne) 
combination.appendAttributedString(partTwo) 
+0

Спасибо за этот простой. –

0

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

Swift 3,0

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

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

result:

Для больше цветов вы можете просто продолжать добавлять атрибуты в изменяемую строку. Другие примеры here.

0

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

Swift 3,0

Здесь я создал класс Helper и метод для

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» как начало строки или какое-либо действительное значение как позиция символа строки length: Int - от местоположения до тех пор, пока не будет использовано количество символов этого стиля.

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

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

Выход:

enter image description here

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

0
func MultiStringColor(first:String,second:String) -> NSAttributedString 
    { 
     let MyString1 = [NSFontAttributeName : FontSet.MonsRegular(size: 14), NSForegroundColorAttributeName : FoodConstant.PUREBLACK] 

     let MyString2 = [NSFontAttributeName : FontSet.MonsRegular(size: 14), NSForegroundColorAttributeName : FoodConstant.GREENCOLOR] 

     let attributedString1 = NSMutableAttributedString(string:first, attributes:MyString1) 

     let attributedString2 = NSMutableAttributedString(string:second, attributes:MyString2) 

     MyString1.append(MyString2) 

     return MyString1 
    } 
1

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:5,length:4)) 
     attributedText = attText 

    } 
} 

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

override func viewDidLoad() { 
     super.viewDidLoad() 

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

    } 
3

Swift 4

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

extension NSMutableAttributedString { 

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

} 

Try над расширением, используя метки:

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) 

Результат:

enter image description here

Смежные вопросы