简体   繁体   中英

Why doesn't the .foregroundColor attribute apply in an NSMutableAttributedString?

I'm trying to create an NSMutableAttributedString by setting the first part of the string a certain color and then the second part bolded. Here is what I've tried so far:

let attributedText = NSMutableAttributedString(string: String.init(format: "#%@ : ", "Field Name"),
                                               attributes: [.foregroundColor: UIColor.gray])
attributedText.append(NSMutableAttributedString(string: String.init(format: "%@", "Sample Field"),
                                         attributes: [.font: UIFont.boldSystemFont(ofSize: 16)]))
myLabel.attributedText = attributedText

What happens here is the second part is successfully bolded, but no color I apply in the first part ever gets reflected. Is there something I'm missing here?

My environment is running Swift 5 in Xcode 12.2.

If you want the same attributes just use a var to keep a reference to them, change the font attribute and use it when you append a new string

let label = UILabel(frame: .init(origin: .zero, size: .init(width: 250, height: 50)))
var attr:  [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.gray]

let attributedText = NSMutableAttributedString(string: .init(format: "#%@ : ", "Field Name"), attributes: attr)
attr[.font] = UIFont.boldSystemFont(ofSize: 16)
attributedText.append(.init(string: .init(format: "%@", "Sample Field"), attributes: attr))

label.attributedText = attributedText
label

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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