I get a message from my response like "your bill is: 10.00"
But I need to show in bold the number and only that (everything after the ":"). I know I could use SubString, but don't understand exactly how to split text and correctly format it
my old test:
self.disclaimerLabel.attributedText = String(format: my).htmlAttributedString(withBaseFont: Font.overlineRegular07.uiFont, boldFont: Font.overlineBold02.uiFont, baseColor: Color.blueyGreyTwo.uiColor, boldColor: Color.blueyGreyTwo.uiColor)
CodePudding user response:
How was my
built ? If from 2 parts, set attributes to each before joining.
If you get my
as a whole, you can access substrings with
let parts = my.split(separator: ":")
parts[1] will be "your bill is" parts[2] will be "10:00"
CodePudding user response:
The need to add styling to a single word or phrase is so common that it is worth having on hand a method to help you:
extension NSMutableAttributedString {
func apply(attributes: [NSAttributedString.Key: Any], to targetString: String) {
let nsString = self.string as NSString
let range = nsString.range(of: targetString)
guard range.length != 0 else { return }
self.addAttributes(attributes, range: range)
}
}
So then your only problem is discovering the stretch of text that you want to apply the attributes to. If you don't know that it is "10.00"
then, as you've been told, you can find out by splitting the string at the colon-plus-space.
CodePudding user response:
You can split your string into char :
and then you can change text attributes like :
var str = "your bill is: 10.00"
var splitArray = str.components(separatedBy: ":")
let normalText = NSMutableAttributedString(string: splitArray[0] ":")
let boldText = splitArray[1]
let boldTextAtr = NSMutableAttributedString(string: boldText, attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16.0) ])
normalText.append(boldTextAtr)
let labell = UILabel()
labell.attributedText = normalText
labell.attributedText will print what you exactly want