1

Currently, I have an UITextView (with scrolling disabled - UITextView inside UIScrollView with AutoLayout)

inside a UIScrollView.

We would like to programmatically highlight selected text. This is what we have done.

@IBAction func click(_ sender: Any) {
    let attributedText = textView.attributedText!
    
    let attributedString: NSMutableAttributedString = NSMutableAttributedString(attributedString: attributedText)
    
    let range = NSRange(location: 0, length: attributedString.length)
    
    attributedString.removeAttribute(NSAttributedString.Key.backgroundColor, range: range)
    
    let searchedString = "Can you highlight and scroll?"
    
    do {
        let regex = try NSRegularExpression(
            pattern: NSRegularExpression.escapedPattern(for: searchedString),
            options: .caseInsensitive
        )
        
        let targetedString = attributedString.string
        
        for match in regex.matches(in: targetedString, options: .withTransparentBounds, range: range) {
            print(">>>> found the 1st match")
            attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.yellow, range: match.range)
            break
        }
    } catch {
        print("\(error)")
    }
    
    textView.attributedText = attributedString
}

It works as shown in the following video.

enter image description here

Instead of manual scrolling, we also like to perform programmatically scrolling, to make the highlighted text visible.

Take note that, performing the following code will not able to achieve what we want

textView.scrollRangeToVisible(match.range)

This is because scrolling is disabled in UITextView

I was wondering, what is a proper way, for me to perform highlight and scroll UITextView inside a UIScrollView?

Demo: https://github.com/yccheok/programming-issue/tree/main/highlight-and-scroll/demo

Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875
  • You might be able to get the rect of the text with https://stackoverflow.com/questions/34922331/getting-and-setting-cursor-position-of-uitextfield-and-uitextview-in-swift with `UITextPosition` – Larme Feb 28 '23 at 17:52
  • @Cheok Could you check and try this - https://stackoverflow.com/a/20229969/3683408 ? – Ram Mar 01 '23 at 15:10

1 Answers1

1

You can do something like this, you use boundingRect(forGlyphRange:in:) on the textView layoutManager to get the Rect for the specific range then use scrollView to scroll to the specific rect full example code

import UIKit

class ViewController: UIViewController {
    var button = UIButton()
    var textView = UITextView()
    let scrollView = UIScrollView()

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .black
    scrollView.backgroundColor = .clear
    textView.backgroundColor = .clear
    
    view.addSubview(scrollView)
    scrollView.translatesAutoresizingMaskIntoConstraints = false
    
    NSLayoutConstraint.activate([
        scrollView.topAnchor.constraint(equalTo: view.topAnchor),
        scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        scrollView.rightAnchor.constraint(equalTo: view.rightAnchor),
        scrollView.leftAnchor.constraint(equalTo: view.leftAnchor),
    ])
    
    
    textView.isScrollEnabled = false
    textView.isEditable = false
    textView.clipsToBounds = true
    
    textView.translatesAutoresizingMaskIntoConstraints = false
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setTitle("Button", for: .normal)
    button.backgroundColor = .red
    button.addTarget(self, action: #selector(buttonCLicked), for: .touchUpInside)
    scrollView.addSubview(button)
    scrollView.addSubview(textView)
    
    
    NSLayoutConstraint.activate([
        button.topAnchor.constraint(equalTo: scrollView.topAnchor),
        button.rightAnchor.constraint(equalTo: scrollView.rightAnchor),
        button.leftAnchor.constraint(equalTo: scrollView.leftAnchor),
        button.heightAnchor.constraint(equalToConstant: 44),
        
        textView.topAnchor.constraint(equalTo: button.bottomAnchor),
        textView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
        textView.rightAnchor.constraint(equalTo: scrollView.rightAnchor),
        textView.leftAnchor.constraint(equalTo: scrollView.leftAnchor),
        textView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1)
    ])
    
    
    let text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident,\n\n\n Can you highlight and scroll? \n\n\nLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of sometimes on purpose (injected humour and the like)."
    
    
    
    let attributedString: NSMutableAttributedString = NSMutableAttributedString(attributedString: NSAttributedString(string: text))
    let range = NSRange(location: 0, length: attributedString.length)
    
    attributedString.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.white, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20)], range: range)
    
    textView.attributedText = attributedString

    
}

@objc func buttonCLicked() {
    let attributedString: NSMutableAttributedString = NSMutableAttributedString(attributedString: textView.attributedText!)
    let range = NSRange(location: 0, length: attributedString.length)
    
    attributedString.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.white, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20)], range: range)
    
    let searchedString = "Can you highlight and scroll?"
    var machedRange:NSRange?
    do {
            let regex = try NSRegularExpression(
                pattern: NSRegularExpression.escapedPattern(for: searchedString),
                options: .caseInsensitive
            )
            
            let targetedString = attributedString.string
            
            for match in regex.matches(in: targetedString, options: .withTransparentBounds, range: range) {
                attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.yellow, range: match.range)
                attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.black, range: match.range)
                
                machedRange = match.range

                break
            }
        } catch {
            print("\(error)")
        }
    
    textView.attributedText = attributedString
    guard let machedRange else {return}
    let buttonHeight:CGFloat = 44
    let margin:CGFloat = 100
    let rect = self.textView.layoutManager.boundingRect(forGlyphRange: machedRange, in: self.textView.textContainer)
    self.scrollView.scrollRectToVisible(CGRect(x: rect.minX, y: rect.minY + buttonHeight + margin, width: rect.width, height: rect.height), animated: true)
    
    
   }

}

Sorry for small gif i couldn't make it bigger :D image

Ahmed Mohiy
  • 190
  • 1
  • 7