注意點:
在textview中計算string占據的高度不能使用[NSStringsizeWithFont:constrainedToSize:],因為textView顯示文字有自己的樣式,在上下左右都有一定的偏移,所以先設置textView.text屬性,然后調用[UITextView sizeThatFits:(CGSize)size] 此函數返回的size就是在textview中text顯示的區域大小。
- - (void)textViewDidChange:(UITextView *)textView
- {
- [textView flashScrollIndicators]; // 閃動滾動條
- static CGFloat maxHeight = 130.0f;
- CGRect frame = textView.frame;
- CGSize constraintSize = CGSizeMake(frame.size.width, MAXFLOAT);
- CGSize size = [textView sizeThatFits:constraintSize];
- if (size.height >= maxHeight)
- {
- size.height = maxHeight;
- textView.scrollEnabled = YES; // 允許滾動
- }
- else
- {
- textView.scrollEnabled = NO; // 不允許滾動,當textview的大小足以容納它的text的時候,需要設置scrollEnabed為NO,否則會出現光標亂滾動的情況
- }
- textView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, size.height);
- }