0

How can I get the whole text in the blue rectangle, inside UITextView, if user select a portion like this:

enter image description here

My current code is to get only the selected text:

if let range = textView.selectedTextRange {
    let selectedText = textView.text(in: range) {
        //selectedText
    }
}
Warren Burton
  • 17,451
  • 3
  • 53
  • 73
Hassan Taleb
  • 2,350
  • 2
  • 19
  • 24
  • textView.text gets the text – stevenpcurtis Mar 12 '21 at 14:26
  • No I want the text in the blue rectangle , not the text in all textView – Hassan Taleb Mar 12 '21 at 14:29
  • You’ll find the methods you need in NSLayoutManager https://developer.apple.com/documentation/uikit/nslayoutmanager which you can access from the textView instance. – Warren Burton Mar 12 '21 at 15:01
  • *inside the blue rectangle* isn't well defined. It looks like you want all the contiguous lines where any portion of the line is selected, but I'm just guessing there. Can you explain more specifically what your requirements are? Also, if you're going to include code, include enough *actual* code that it's useful; the minimal code that you've provided doesn't tell us anything useful. – Caleb Mar 12 '21 at 15:13

1 Answers1

3

You have to set your view controller as the text view delegate UITextViewDelegate

override func viewDidLoad() {
    super.viewDidLoad()
    textView.delegate = self
}

Implement textViewDidChangeSelection method

func textViewDidChangeSelection(_ textView: UITextView)

In this function you can get the UITextPosition of the start and end of the lines of the selection, then create a new range and retrieve the selected text:

func textViewDidChangeSelection(_ textView: UITextView) {
    guard let selectedTextRange = textView.selectedTextRange,
          let start = textView.tokenizer
            .position(from: selectedTextRange.start, toBoundary: .line, inDirection: .backward),
           let end = textView.tokenizer
            .position(from: selectedTextRange.end, toBoundary: .line, inDirection: .forward),
           let range = textView.textRange(from: start, to: end),
           let text = textView.text(in: range)
    else { return }
    print(text)
}

Add this extension helpers to your project:

extension UITextDirection {
    static let forward: Self = .init(rawValue: 0)
    static let backward: Self = .init(rawValue: 1)
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571