2015-01-01 54 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更新回答。

首先如下初始化你的NSStringNSMutableAttributedString

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

为雨燕4更新回答

您可以轻松地使用的attributedText属性里面的html 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

为夫特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'的类型为'(data:NSData,options:[String:String],documentAttributes:_,error:_')的参数列表' –

+2

Swift 2中有更改。请检查我的更新答案。 – rakeshbs

6

使用rakeshbs的回答创造斯威夫特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 

关于延长的好处是,你必须在你的整个应用程序的所有String小号.attributedStringFromHtml属性。

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 

夫特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

我喜欢它使用HTML版本这样

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

夫特3例子。

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

雨燕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

这里是支持最新版本夫特作为年03月2017

夫特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 
    } 
} 
一个Helper类和方法的代码

在方法参数中, inputText:String - 要在标签中显示的文本 位置:Int - 其中样式应该是应用程序,“0”作为字符串的开始或某个有效值作为字符串的字符位置。 length:Int - 从该位置开始直到此样式适用的字符数。

在其它方法消耗:

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

输出:

enter image description here

注:UI颜色可以定义颜色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

斯威夫特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) 
    } 

} 

尝试了上述扩展,使用标签:

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