2014-05-21 36 views
1
- (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; 
} 

問題計數 「\ n」 表示sizeWithFont:constrainedToSize:給我的錯高度。 例如,如果文字是Hello \nsizeWithFont不會算\n, 所以「你好」Hello \n文本是在同一高度sizeWithFont:constrainedToSize:不中的NSString

任何必要的幫助將不勝感激!

+1

如果要在\ n之後添加空格怎麼辦? 「你好\ n」 – nerowolfe

+0

Tnx!它現在工作:) – PizzaByte

回答

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