首页 > 解决方案 > 将具有不同样式的文本添加到现有标签

问题描述

我有一个带有文本的标签,想在运行时添加更多测试,但我想为这个添加的文本添加不同的样式。有没有办法做到这一点?

这是代码

label.text = (label.text ?? "") + " \n  \(userName)"

如何在userName不更改标签样式的情况下添加样式?

标签: iosswift

解决方案


为此,您需要使用 NSMutableAttributedString、NSAttributedString 并使用 label.attributedText,如何?

这样做:

let userName = "StackOverflow"
    let prefixText = NSAttributedString(string: "this is normal ")
    let font = UIFont.systemFont(ofSize: 40)
    let attributes: [NSAttributedString.Key: Any] = [
        .font: font,
        .foregroundColor: UIColor.blue
    ]
    let userNameWithStyle = NSAttributedString(string: userName, attributes: attributes)

    let finalString = NSMutableAttributedString(attributedString: prefixText)
    finalString.append(userNameWithStyle)
    self.label.attributedText = finalString

图像结果


推荐阅读