Search code examples
iosobjective-cuitextviewuitextrange

Move Cursor to Beginning of Prepopulated Textview On Load in Objective-C


Upon a View Controller loading from code where a UITextView is prepopulated with some text, I would like the cursor to be at the beginning of the text not at the end.

The following code however is having no effect. The cursor still appears at the end of the prepopulated text.

What can I do to get the cursor over to the beginning of the text?

   self.myTextView.text = @"Text that should go after cursor";
    [self.myTextView becomeFirstResponder];      
    UITextPosition* start = self.myTextView.beginningOfDocument;
    UITextRange *newRange = [self.myTextView textRangeFromPosition:start toPosition:start];
NSLog("newRange is%@",newRange);
    [self.myTextView setSelectedTextRange:newRange];

Note, newRange logs as <_UITextKitTextRange: 0x17463f0c0> (0, 0)F so I think the next line is not actually changing the rang. But I don't know of another way to do this.


Solution

  • I found that your print was wrong, missing an @

    NSLog(@"newRange is%@",newRange);
    

    Then I found that your code is effective, the cursor can be positioned to the front

    I tested iOS 9.1iOS 10.1iOS 11.1iOS 12.4 with the simulator, all of which are effective. I don't know what your environment is like.

    One more thing to note is that before executing that piece of code, make sure that myTextView has been created successfully. I used storyboard to create myTextView when I tested, and added your code in viewDidLoad.