我刚刚完成了这个。当前(发布此答案时)接受的答案的问题是委托方法:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
在提交用户键入/插入/删除的更改之前公开 textView。因此,您将要实现的调整大小将晚一个字符。UITextView 确实从 UIScrollView 继承,因此文本不会从屏幕上剪掉,但可能会导致一些尴尬的行为。
我的解决方案是使用两个委托方法来正确实现调整大小的效果。
在用户键入的字符到达屏幕之前展开 UITextView:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
NSMutableString *tempString = [NSMutableString stringWithString:textView.text];
[tempString replaceCharactersInRange:range withString:text];
//If we are adding to the length of the string (We might need to expand)
if([tempString length]>textView.text.length)
{
//Create a temporaryTextView which has all of the characteristics of your original textView
UITextView *tempTextView = [[UITextView alloc] initWithFrame:CGRectZero];
tempTextView.font = _inputFont;
tempTextView.contentInset = textView.contentInset;
[tempTextView setText:tempString];
//Change this to respect whatever width constraint you are trying to achieve.
CGSize theSize = [tempTextView sizeThatFits:CGSizeMake(192, CGFLOAT_MAX)];
if(theSize.height!=textView.frame.size.height)
{
textView.frame = CGRectMake(115, 310, 192,theSize.height);
return YES;
}
else
{
return YES;
}
}
else
{
return YES;
}
}
并在用户删除/缩小 UITextView 中的文本量后缩小字符
-(void)textViewDidChange:(UITextView *)textView
{
//We enter this method AFTER the edit has been drawn to the screen, therefore check to see if we should shrink.
if([textView sizeThatFits:CGSizeMake(192, CGFLOAT_MAX)].height!=textView.frame.size.height)
{
//change this to reflect the constraints of your UITextView
textView.frame = CGRectMake(115, 310, 192,[textView sizeThatFits:CGSizeMake(192, CGFLOAT_MAX)].height);
}
}