the Reverend the Reverend - 1 year ago 97
Swift Question

How to get the start of line of the current position in a UITextView

I want to get the start of the line for the current cursor position on a UITextView

First I get the current position, thats easy.

let currentPosition = textView.selectedTextRange!.start

Then I should get the startOfLinePosition with this method, but I´m unsure of how to get the offset

let startOfLinePosition = textView.positionFromPosition(currentPosition, inDirection: .Left, offset: ?)

How can I get the differential offset ?

Answer Source

Use the tokenizer:

let currentPosition = textView.selectedTextRange!.start
let startOfLinePosition = textView.tokenizer.positionFromPosition(currentPosition, toBoundary: .Paragraph, inDirection: UITextStorageDirection.Backward.rawValue)!
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download