Resize UItextview according to it's content in iOS7

自古美人都是妖i 提交于 2019-11-28 20:53:04
Ivica M.

It seems UITextView's contentSize property is not correctly set in iOS 7 till viewDidAppear:. This is probably because NSLayoutManager lays out the text lazily and the entire text must be laid out for contentSize to be correct. The ensureLayoutForTextContainer: method forces layout of the provided text container after which usedRectForTextContainer: can be used for getting the bounds. In order to get total width and height correctly, textContainerInset property must be taken into account. The following method worked for me.

 - (CGRect)contentSizeRectForTextView:(UITextView *)textView
    {
        [textView.layoutManager ensureLayoutForTextContainer:textView.textContainer];
        CGRect textBounds = [textView.layoutManager usedRectForTextContainer:textView.textContainer];
        CGFloat width =  (CGFloat)ceil(textBounds.size.width + textView.textContainerInset.left + textView.textContainerInset.right);
        CGFloat height = (CGFloat)ceil(textBounds.size.height + textView.textContainerInset.top + textView.textContainerInset.bottom);
        return CGRectMake(0, 0, width, height);
    }

Additionally, it seems UITextView's setContentSize: method is called from layoutSubviews. So, calling layoutIfNeeded on a textView (which itself calls layoutSubviews) after calling ensureLayoutForTextContainer: on its layoutManager, should make the textView's contentSize correct.

[someTextView.layoutManager ensureLayoutForTextContainer:someTextView.textContainer];
[someTextView layoutIfNeeded]; 
// someTextView.contentSize should now have correct value

GrowingTextViewHandler is an NSObject subclass which resizes text view as user types text. Here is how you can use it.

 @interface ViewController ()<UITextViewDelegate>

 @property (weak, nonatomic) IBOutlet UITextView *textView;
 @property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightConstraint;
 @property (strong, nonatomic) GrowingTextViewHandler *handler;

 @end

 @implementation ViewController

 - (void)viewDidLoad {
   [super viewDidLoad];
   self.handler = [[GrowingTextViewHandler alloc]initWithTextView:self.textView withHeightConstraint:self.heightConstraint];
   [self.handler updateMinimumNumberOfLines:3 andMaximumNumberOfLine:8];
}

 - (void)textViewDidChange:(UITextView *)textView {
   [self.handler resizeTextViewWithAnimation:YES];
}
@end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!