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)
}