我剛剛完成實現這一點。當前的問題(如發佈這個答案)接受的答案是,委託方法:
- (BOOL)的TextView:(UITextView的*)的TextView shouldChangeTextInRange:(NSRange)範圍replacementText:(的NSString *)文本
在更改用戶輸入/插入/刪除之前暴露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);
}
}
這種方法在我輸入時似乎沒有被調用。它應該是? – Mrwolfy
哦,等等,現在是這樣了,因爲我把這一點添加到了viewDidLoad [myTextView setDelegate:self]; – Mrwolfy
查看編輯答案。 –