I have subclassed UITextView
with the goal of introducing placeholder
functionality. It's mostly working well, but I'm having issue with the behaviour when the UITextView
becomes active either by user tap or by calling becomeFirstResponder
. Below is the custom method that gets called whenever a UITextViewTextDidBeginEditingNotification
notification gets fired.
- (void)textViewSelected {
if ([self.text isEqualToString:self.placeholder]) {
NSLog(@"a %@", NSStringFromRange(self.selectedRange));
self.selectedRange = NSMakeRange(0, 0);
NSLog(@"b %@", NSStringFromRange(self.selectedRange));
}
}
Console logs this
a {16, 0}
b {0, 0}
but the cursor is still blinking here
I even tried subclassing the setSelectedRange:
method to check if something sets the range after my method call
- (void)setSelectedRange:(NSRange)selectedRange {
NSLog(@"aa %@", NSStringFromRange(self.selectedRange));
[super setSelectedRange:selectedRange];
NSLog(@"bb %@", NSStringFromRange(self.selectedRange));
}
But the result if as follows:
a {16, 0}
aa {16, 0}
bb {0, 0}
b {0, 0}
which would imply that the cursor should be at index 0.
Anyone has any ideas what is going wrong here?
I couldn't sort out why NSMakeRange(0, 0)
didn't work, but I ended up solving my problem by calling NSMakeRange(0, 0)
with a delay, like so:
[self performSelector:@selector(placeMarkerInTheBeginning) withObject:nil afterDelay:0.01];
And
- (void)placeMarkerInTheBeginning {
self.selectedRange = NSMakeRange(0, 0);
}
Hope this helps someone.