I have an UITextField
with long text inside, I need to find all the occurrences of a string inside the text and make them bold.
I know I should use NSMutableAttributedString
for making the text bold, but how can I search specific substring inside the text?
Asked
Active
Viewed 547 times
-3

Szanownego
- 239
- 1
- 11
-
This question may help: [Find all locations of substring in NSString (not just first)](https://stackoverflow.com/questions/7033574/find-all-locations-of-substring-in-nsstring-not-just-first) – 93xrli Jan 04 '20 at 10:32
1 Answers
1
You can create a textView extension that can be called on your textView outlet:
extension UITextView {
func makeBold(originalText: String, boldText: String) {
let attributedOriginalText = NSMutableAttributedString(string: originalText)
let boldRange = attributedOriginalText.mutableString.range(of: boldText)
attributedOriginalText.addAttribute(NSAttributedString.Key.font, value: UIFont.boldSystemFont(ofSize: 13), range: boldRange)
self.attributedText = attributedOriginalText
}
}
How to use:
@IBOutlet weak var textView: UITextView!
textView.makeBold(originalText: "Make bold", boldText: "bold")

elarcoiris
- 1,914
- 4
- 28
- 30
-
That works great, thanks a lot Is there a way to take only full word occurrence? With this solution if I search "me" It gets bold also the value inside a work (e.g. mercy "me" gets bold but in this case should be avoided) – Szanownego Jan 04 '20 at 12:55
-
Check out the example in this answer for that and take note of the comments for your application https://stackoverflow.com/a/7033787/4844273 – elarcoiris Jan 06 '20 at 05:45