My two localised strings:
"welcome message" = "%@ has joined %@";
"welcome message" = "انضم %@ إلى %@";
Results


extension String {
func localisedAttributedString(_ replacements: CVarArg..., attributes: [NSAttributedString.Key : Any], replacementAttributes: [[NSAttributedString.Key : Any]?] ) -> NSAttributedString {
let message = String.init(format: NSLocalizedString(self, comment: ""), arguments: replacements)
let attributedString = NSMutableAttributedString(string: message, attributes: attributes)
for (i, replacement) in replacements.enumerated() {
if let att = replacementAttributes[i] {
let range = (attributedString.string.range(of: "\(replacement)".localized)?.nsRange(in: attributedString.string)) ?? NSRange(location: 0, length: 0)
attributedString.addAttributes(att as [NSAttributedString.Key : Any], range: range)
}
}
return attributedString
}
}
HOW TO USE
//General attr: Applied to the entire string
let generalAttributes = [NSAttributedString.Key.font: UIFont.getFont(.regular, size: 20)]
//Additional attrs applied to the replacement / dynamic bits. You can pass nil too
let nameAttributes = [ NSAttributedString.Key.backgroundColor: UIColor.red]
let companyAttributes = [ NSAttributedString.Key.foregroundColor: UIColor.blue]
myLabel.attributedText = "welcome message".localisedAttributedString("adam".localized, "space".localized, attributes: generalAttributes, replacementAttributes: [nameAttributes, companyAttributes] )
NSAttributedStringfrom HTML Text (all tags are not translated, but just the bold/color are managed): stackoverflow.com/questions/39248092/… So adding<b>and others should do the trick.