Reputation: 655
I'm looking for a behaviour similar to the Notes app. It automatically saves the first row of text as the views name. My code below saves the text entered upon pressing Return as the UIView's title. The problem I'm encountering is that If I press Return before entering any text, and then enter some text and press Return again, it won't save it.
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
NSMutableString *newString = [NSMutableString stringWithString:textView.text];
[newString replaceCharactersInRange:range withString:text];
NSRange newLineRange = [newString rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet]];
if(newLineRange.length > 0)
{
self.title = [newString substringToIndex:newLineRange.location];
}
else {
self.title = textView.text;
}
return YES;
}
Any suggestions?
Upvotes: 3
Views: 495
Reputation: 726579
The problem with your code is that it finds the first newline, and uses a substring from zero to its location as the title. Trimming the string before looking for the newline should fix this problem: the first non-empty line, if any, would be selected for the title:
[newString replaceCharactersInRange:range withString:text];
NSString *trimmed = [newString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSRange newLineRange = [trimmed rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet]];
if(newLineRange.length > 0)
{
self.title = [trimmed substringToIndex:newLineRange.location];
}
else {
self.title = trimmed;
}
Upvotes: 2