I have a UITextView which is editable. Now I have a requirement which requires me to find (as and when I keep typing) as to when the next line has begun (maybe due to me hitting the return key, or an auto wordwrap linebreak). Is there any notification which can be obtained to figure out when the next line has started while typing?
I tried searching for solutions to find out cursor positions within a textview but using selectedRange and the location properties to find it out does not help me. There is no correlation at all between the location value and a new line. The location value just keeps increasing on typing. Any ideas?
Thanks!
The following delegate is called whenever a new text is entered in textView.
Set the delegate for UITextView, then code as follows
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
{
if ( [text isEqualToString:@"\n"] ) {
//Do whatever you want
}
return YES;
}
For Swift use this
previousRect = CGRectZero
func textViewDidChange(textView: UITextView) {
var pos = textView.endOfDocument
var currentRect = textView.caretRectForPosition(pos)
if(currentRect.origin.y > previousRect?.origin.y){
//new line reached, write your code
}
previousRect = currentRect
}
For Objective C
CGRect previousRect = CGRectZero;
- (void)textViewDidChange:(UITextView *)textView{
UITextPosition* pos = textView.endOfDocument;
CGRect currentRect = [textView caretRectForPosition:pos];
if (currentRect.origin.y > previousRect.origin.y){
//new line reached, write your code
}
previousRect = currentRect;
}
Will detect line changes from anything to hitting "return", backspacing to reduce line-count, typing till the end of the line and a word-wrap occurs, etc. (*Note: MUST adjust variables for font size, I recommend not using hard coded numbers like in my example below).
previousNumberOfLines = ((hiddenText.contentSize.height-37+21)/(21));//numbers will change according to font size
NSLog(@"%i", previousNumberOfLines);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With