sizeWithFont:constrainedToSize:不计算" \ n"在NSString中

时间:2014-05-21 09:10:17

标签: ios objective-c nsstring uitextview sizewithfont

- (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;
}

问题是 sizeWithFont:constrainedToSize: 给了我错误的高度。 例如,如果文字Hello \n sizeWithFont将不计算\n, 所以“Hello”Hello \n文字处于相同的高度

任何需要的帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

不相关,但获得substring的方式忽略了文本修改的范围。

- (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];
    ...
}