Search code examples
iosswiftuitextfieldnsmutableattributedstring

Swift - search strings in TextView and make them bold


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?


Solution

  • 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")