sizeWithFont:constrainedToSize: Doesn't count "\n" in NSString

157 Views Asked by At
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    NSString *substring = textView.text;
    substring = (text.length == 0 && range.length == 1) ?
    [substring substringToIndex: substring.length-1] : [substring stringByAppendingString: text];

    CGSize size = [substring sizeWithFont:textView.font
                        constrainedToSize:CGSizeMake(textView.frame.size.width, 200.0)];

    CGFloat height = MAX(size.height, firstHeight);

    if(height != lastHeight)
    {
        CGFloat y = height - lastHeight;
        CHANGE_HEIGHT(textView, height);
        lastHeight = height;
    }   
    return YES;
}

The issue is that sizeWithFont:constrainedToSize: gives me the wrong height. For example if text is "Hello \n" sizeWithFont will not count the "\n", so "Hello" and "Hello \n" texts are in the same height.

Any needful help will be appreciated!

1

There are 1 best solutions below

0
On

Unrelated but the way you get your substring is ignoring the range where the text is modified.

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    NSString *textToMeasure = [textView.text stringByReplacingCharactersInRange:range withString:text];
    if ([textToMeasure hasSuffix:@"\n"]) {
        textToMeasure = [NSString stringWithFormat:@"%@-", textView.text];
    ...
}