Linh
Linh

Reputation: 60973

IOS - Is it posible to calculate TextView height before it's drawn

I have a custom PopupView(extends UIView). PopupView only contains TextView.
The width of PopupView is 220.
Now I want the PopupView height depend on TextView height like when TextView is short the popup will short.
Can I calculate TextView height before shown the PopUp?

Here is what I have done to make PopupView height depends on TextView height.
- I show the PoupView with the width and height = screen width and height
- After that I calculate TextView height after it drawn (in layoutSubviews)
- Then I update PopupView height
=> It will be better if I can get the TextView height before it's drawn

- (void)layoutSubviews{
     [self.textView layoutIfNeeded];
     CGSize sizeThatShouldFitTheContent = [self.contentTextView sizeThatFits:self.textView .frame.size]; // this return correct value of `TextView` height
     // After I get textview height, I update contraint height of PopupView
}

Upvotes: 0

Views: 177

Answers (1)

FreeNickname
FreeNickname

Reputation: 7814

This is not what you asked for, but it is probably what you need: just remove the height constraint of the popup view, and disable scrolling for the text view (if scrolling is enabled, the default height is 0, otherwise the text view is resized automatically to fit the content). This way popup will wrap the text view.

You need to set constraints like so:

TextView.Top = Popup.Top
TextView.Left = Popup.Left
TextView.Right = Popup.Right
TextView.Bottom = Popup.Bottom
Popup.Width = <some fixed value> //Yay! Stairs :)

You can disable scrolling either programmatically: textView.scrollingEnabled = NO; or via the interface builder.

Upvotes: 1

Related Questions