swift - 带有字符串插值的属性字符串不起作用(swift)

标签 swift string string-interpolation

我想在字符串插值中使用属性字符串。但它的工作原理如屏幕截图中所示。属性字符串的格式不正确。为什么会发生这种情况?有没有其他方法可以解决这个问题?

enter image description here

@IBOutlet weak var denemeLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()


        var nameString: String = "any String"
            denemeLabel.text = ""

            let nameAttribute = [NSAttributedString.Key.font: UIFont(name: "Chalkduster", size: 18)]
            let attributedNameString = NSMutableAttributedString(string: nameString, attributes: nameAttribute)

            let nsAttributedString =  NSMutableAttributedString(string:"\(attributedNameString) another String")
            denemeLabel.attributedText = nsAttributedString

    }

最佳答案

Xcode 10.1 Swift 4.2

var nameString: String = "any String"

// Set Attributes for the first part of your string
let att1 = [NSAttributedString.Key.font : UIFont(name: "Chalkduster", size: 18.0)]

// Set Attributes for the second part of your string
let att2 = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 18)]

// Create the first part of your attributed string
let attributedString1 = NSMutableAttributedString(string: nameString, attributes: att1)

// Create the second part of your attributed string
let attributedString2 = NSMutableAttributedString(string: "another String", attributes: att2)

// Append the second string to the end of the first string
attributedString1.append(attributedString2)

// Update your label
denemeLabel.attributedText = attributedString1

enter image description here

关于swift - 带有字符串插值的属性字符串不起作用(swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54966117/

相关文章:

ios - 客户端和服务器上都无法使用 socket.io 连接到服务器

ios - 在 Swift 中的自定义单元格之间切换

c - 如何打印包含特殊字符并从文件中读取的字符串?如何打印没有特殊字符?

Java- 拆分字符串,它是字母数字

ios - 在 iOS 13 上隐藏导航栏分隔线

ios - 访问 Firebase 数据库 Swift 3 中的多级嵌套子级

raku - 用 qq 括号分隔符不要在 Raku 中插入代码

string - 如何对分类数据进行插值

python - 在python中打印出$和*+2字符之间的所有字符串

dictionary - 如何访问模板字符串中的 map ?