简体   繁体   English

带字符串插值的属性字符串不起作用(快速)

[英]Attributed String with String interpolation does not work(swift)

I want to use an attributed string in string interpolation. 我想在字符串插值中使用属性字符串。 but it works as it appears in the screenshot. 但它的工作原理与屏幕截图中显示的一样。 the attributed string is not formatted the right way. 属性字符串的格式不正确。 why does this happen? 为什么会这样? Is there an alternative way to overcome this problem? 是否有其他方法可以解决此问题?

在此处输入图片说明

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM