I'm trying to resize a text view according to content & also it's sibling and parent container.
Below code is working fine in iOS 6
if (/* less than ios 7 */) {
CGRect frame = _textView.frame;
CGSize conSize = _textView.contentSize;
CGFloat difference = conSize.height - frame.size.height;
frame.size.height += difference;
_textView.frame = frame;
UIScrollView *parentView = (UIScrollView *)_textView.superview;
// adjust views residing below this text view.
// sibling view
UIView *belowView = // access it somehow
CGRect frame1 = belowView.frame;
frame1.origin.y += difference;
belowView.frame = frame1;
// adjust parent scroll view, increase height.
CGSize frame3 = parentView.contentSize;
frame3.height += difference;
parentView.contentSize = frame3;
} else {
// tried
[_textView sizeToFit];
[_textView layoutIfNeeded];
[parentView sizeToFit];
[parentView layoutIfNeeded];
}
Tried to follow iOS 7 solution from: How do I size a UITextView to its content on iOS 7?
but not working.
Any pointers?
Working code solution from @NSBouzouki
if (/* ios 7 */) {
[_textView.layoutManager ensureLayoutForTextContainer:_textView.textContainer];
[_textView layoutIfNeeded];
}
CGRect frame = _textView.frame;
CGSize conSize = _textView.contentSize;
CGFloat difference = conSize.height - frame.size.height;
frame.size.height += difference;
_textView.frame = frame;
UIScrollView *parentView = (UIScrollView *)_textView.superview;
// adjust views residing below this text view.
// sibling view
UIView *belowView = // access it somehow
CGRect frame1 = belowView.frame;
frame1.origin.y += difference;
belowView.frame = frame1;
// adjust parent scroll view, increase height.
CGSize frame3 = parentView.contentSize;
frame3.height += difference;
parentView.contentSize = frame3;
It seems
UITextView's
contentSize
property is not correctly set in iOS 7 tillviewDidAppear:
. This is probably becauseNSLayoutManager
lays out the text lazily and the entire text must be laid out forcontentSize
to be correct. TheensureLayoutForTextContainer:
method forces layout of the provided text container after whichusedRectForTextContainer:
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.Additionally, it seems
UITextView's
setContentSize:
method is called fromlayoutSubviews
. So, callinglayoutIfNeeded
on atextView
(which itself callslayoutSubviews
) after callingensureLayoutForTextContainer:
on itslayoutManager
, should make thetextView's
contentSize
correct.GrowingTextViewHandler is an NSObject subclass which resizes text view as user types text. Here is how you can use it.