我想在字符串插值中使用属性字符串。但它的工作原理如屏幕截图中所示。属性字符串的格式不正确。为什么会发生这种情况?有没有其他方法可以解决这个问题?
@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
关于swift - 带有字符串插值的属性字符串不起作用(swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54966117/