2014-05-21 17 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]; 
    ... 
}