views:

23

answers:

0

I have a UITextView that I would like to change the auto capitalization type to words for just the first line of the text and reset it to sentences for every other line. What's the best way to do this?

My initial thought is that I can calculate the average maximum number of letters that would fit on a line and recalculate that once any time the font changes. This could be done by taking an arbitrary lorem ipsum string and testing the size. This is the (absurdly long named method) I came up with to try that along with the textView delegate method:

- (int) calculateAverageLengthofStringInFirstLineOfTextforTextView:(UITextView *)textView {
NSString *testString = @"Lorem ipsum dolar sit met, integer tort or rises, placerat seed a turps. Luctus leo id mas a faucibus vulputate. Mauris conga ornare mauris.";
CGSize lineSize = [testString sizeWithFont:self.defaultFont];
int i = [testString length];

while(i>0 && lineSize.width < textView.frame.size.width)
{
    lineSize = [[testString substringToIndex:i] sizeWithFont:self.defaultFont];
    DLog(@"line: %f view: %f", lineSize.width, textView.frame.size.width);

    i = i - 5;
}

return i;

}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
if (range.location <= self.firstLineOfTextLength)
    self.notesTextView.autocapitalizationType = UITextAutocapitalizationTypeWords;
else
    self.notesTextView.autocapitalizationType = UITextAutocapitalizationTypeSentences;

return YES; }

This approach doesn't work, however. For one, the comparison lineSize.width < textView.frame.size.width seems to incorrectly evaluate to true even if the lineSize.width is greater. For another, even if the correct size is determined, setting the notesTextView.autoCapitalizationType in the shouldChangeTextInRange doesn't seem to do anything.

What's the correct approach to make this work?