You can use NSAttributedString
and append text and attributes:
let normalAttrs = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15)]
let boldAttrs = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 15)]
let partOne = NSMutableAttributedString(string: "Your score is ", attributes: normalAttrs)
let partTwo = NSMutableAttributedString(string: "perfect".localized(), attributes: boldAttrs)
let partThree = NSMutableAttributedString(string: ".", attributes: normalAttrs)
partOne.append(partTwo)
partOne.append(partThree)
myLabel.attributedText = partOne
Edit:
Here's a more flexible approach using NSMutableAttributedString
's
replaceCharacters(in range: NSRange, with attrString: NSAttributedString)
This will make it easy to replace "%@"
in your localized string with a localized version of the "score word", regardless of length or position:
class TestViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// simulate localized strings
let localizedStrings = [
"Your score is %@.",
"You got a %@ score.",
"%@ is your final score.",
]
let localizedPerfects = [
"Perfect",
"Perfekt",
"Perfectamente",
]
let normalAttrs = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15)]
let boldAttrs = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 15)]
var y = 40
for (scoreString, perfectString) in zip(localizedStrings, localizedPerfects) {
// add a label
let label = UILabel()
view.addSubview(label)
label.frame = CGRect(x: 20, y: y, width: 280, height: 40);
y += 40
if let rangeOfPctAt = scoreString.range(of: "%@") {
let attStr = NSMutableAttributedString(string: scoreString, attributes: normalAttrs)
let attPerfect = NSAttributedString(string: perfectString, attributes: boldAttrs)
let nsRange = NSRange(rangeOfPctAt, in: attStr.string)
attStr.replaceCharacters(in: nsRange, with: attPerfect)
label.attributedText = attStr
} else {
// "%@" was not in localized score string
label.text = "invalid score string format"
}
}
}
}
Result:
