ios - 在单个标签中使用多种字体颜色

标签 ios swift uilabel nsattributedstring textcolor

有没有办法在 iOS 的单个标签中使用两种甚至三种字体颜色?

如果以文本“你好,你好吗”为例,“你好”会是蓝色,而“你好吗”会是绿色?

这可能吗,这似乎比创建多个标签更容易?

最佳答案

Reference from here.

首先初始化 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

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))

关于ios - 在单个标签中使用多种字体颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27728466/

相关文章:

ios - 我如何在 UITableView 中检测手机屏幕中部署的单元格是什么

swift - 在 case 语句中覆盖一系列字符串?

ios - 如何在 touchesBegan 上调整自定义 UIView 中的 UILabel 位置?

iphone - 同一文本中的多种颜色

ios - 将图像和标签保存并检索到下一个 View 。代码

ios - 使用 MapKit 生成特定距离的路线

ios - Xcode 界面生成器 : Static table view cell font is not being set

ios - 导致黑屏的 SWRevealViewController 层次结构

arrays - Swift 3 - 无法使用数组发出 Alamofire 请求

swift - 泛型中的 T 等于 T 是什么意思