iosiphoneuitextviewcursor-positiontext-cursor

How to move cursor to the beginning of the current line in UITextView?


I want to have an insert tab button for my UITextView so that users be able to insert a tab at beginning of the current line. No matter where the cursor is in the line, the tab should be inserted at the beginning of the line, and after that the cursor must go to the end of the line.

Is it possible ?


Solution

  • I have no luck with positionFromPosition:inDirection:offset: and characterRangeByExtendingPosition:inDirection:.

    But this works fine for me:

    UITextRange *range = [textView selectedTextRange];
    CGRect rect = [textView caretRectForPosition:range.start];
    UITextPosition *start = [textView closestPositionToPoint:CGPointMake(0, rect.origin.y)];
    [textView setSelectedTextRange:[textView textRangeFromPosition:start toPosition:start]];
    

    UPD: the code above is tested on iOS7 and earlier. And can no longer work with iOS9. Actually, I have some bugs in my text-editing app running on iOS9-devices. I'll update my answer after fixing my app.