For doing multiple occurrence of words to be bold in string you can use this function directly or in String extension.
func addBoldText(text: String, substringsToBold: Array<String>, regularFont: UIFont, boldFont: UIFont) -> NSAttributedString {
// Create an attributed string
let attributedString = NSMutableAttributedString(string: text)
// Apply regular font to the entire string
attributedString.addAttributes([.font: regularFont], range: NSRange(location: 0, length: text.utf16.count))
// Apply bold font to specific substrings
for substringToBold in substringsToBold {
var searchRange = NSRange(location: 0, length: text.utf16.count)
while let range = text.range(of: substringToBold, options: .caseInsensitive, range: Range(searchRange, in: text)) {
attributedString.addAttributes([.font: boldFont], range: NSRange(range, in: text))
searchRange.location = range.upperBound.utf16Offset(in: text)
searchRange.length = text.utf16.count - searchRange.location
}
}
return attributedString
}}
And how you will be gonna use this:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Create a string
let text = "Hello, World! This is the world we live in. Welcome to the world."
// Define font attributes for regular and bold text
let regularFont = UIFont.italicSystemFont(ofSize: 18)
let boldFont = UIFont.boldSystemFont(ofSize: 18)
// Define an array of substrings to make bold
let substringsToBold = ["Hello", "world", "Welcome"]
let label = UILabel()
label.attributedText = addBoldText(text: text, substringsToBold: substringsToBold, regularFont: regularFont, boldFont: boldFont)
label.numberOfLines = 0
label.frame = self.view.frame
self.view.addSubview(label)
}
Please check a scrrenshot
titleLabel.font = UIFont.boldSystemFont(ofSize: 11)
working perfect – Speak