首页 > 解决方案 > NSAttributedString 未返回预期值

问题描述

我正在尝试创建如下文本:比尔开始关注你。” 并使用户名半粗体。我试过了,但是 .string 给了我一个奇怪的长字符串。我该如何解决?

        //let nUsername = username
    let fontU = UIFont(name: "SFCompactDisplay-Semibold", size: 15)
    let fontN = UIFont(name: "SFCompactDisplay-Regular", size: 15)

    let usernameAttributes = [NSAttributedString.Key.font: fontU]
    let notifAttributes = [NSAttributedString.Key.font: fontN]

    let firstString = NSMutableAttributedString(string: username, attributes: usernameAttributes)
    let secondString = NSAttributedString(string: " started following you.", attributes: notifAttributes)

    firstString.append(firstString)
    firstString.append(secondString)

    //notifInfoLabel.frame = CGRect(x: 77, y: 15, width: 295, height: 18)
    notifInfoLabel.text = "\(firstString.string)"

标签: iosswiftnsattributedstring

解决方案


摆脱:

firstString.append(firstString)

这重复了用户名。

而且您没有使用最终的属性字符串。利用:

notifInfoLabel.attributedText = firstString

推荐阅读