Reputation: 405
I try to move the cursor when a UITextView
is selected(touched) to simulate kind of a UITextField placeholder
thing.
I'd like the cursor to be at the beginning of the first line. My problem is, that [someTextField setSelectedRange]
is not working reliably. When I call it in textView:shouldChangeTextInRange:replacementText:
it works as it should. But this method is only called when the user starts typing. I'm using textViewDidBeginEditing:
to move the cursor when the UITextView
becomes the first responder:
- (void)textViewDidBeginEditing:(UITextView *)textView
{
if (textView == self.descriptionText) {
CustomTextView* customTV = (CustomTextView *)textView;
if ([customTV.text isEqualToString:customTV.placeholder]) {
// text in text view is still the placeholder -> move cursor to the beginning
customTV.text = customTV.placeholder;
customTV.textColor = [UIColor lightGrayColor];
customTV.selectedRange = NSMakeRange(0, 0);
}
}
}
Any ideas why customTV.selectedRange = NSMakeRange(0, 0);
isn't working correctly in textViewDidBeginEditing:
?
Thanks for your help!
Upvotes: 2
Views: 1024
Reputation: 242
Actually there's a very simple way of accomplishing this.
// Count the characters on screen
NSMutableString *numOfChar = [self.myTextField.text mutableCopy];
// Skip that many characters to the left
self.myTextField.selectedRange = NSMakeRange(self.myTextField.selectedRange.location-[numOfChar length], 0);
Hope this helps.
Upvotes: 2