Dancer
Dancer

Reputation: 17651

UITextView within UIScrollView - Dynamic Heights?

I have a UIView which contains a UIScroller - which in turn contains a couple of labels, one image and a dynamic text view.

The text view can contain anything from a few characters to 2000 words - how can I automatically apply the relevant heights to the UITextView and the parent scroller?

I have got as far as the following -

//Set Scroller
[self.scrollerArticle setScrollEnabled:YES];
[self.scrollerArticle setContentSize:CGSizeMake(320, 750)];
[self.articleUITextView sizeToFit];
[self.articleUITextView layoutIfNeeded];

But don't know how to apply the sizetofit method to the scroller?

Upvotes: 1

Views: 1525

Answers (3)

Gyanendra Singh
Gyanendra Singh

Reputation: 1483

You can get the height of the content using the below method.

-(CGFloat)getContentHeight{

NSString *aMessage = @"My Name is ABC"; // Can be anything between 0 to 2000 chars

CGSize maximumSize = CGSizeMake(320, 9999);

// Use the font you are willing to use for TexTView.
UIFont *textFont = [UIFont fontWithName:@"Helvetica-Bold" size:MessageFontSize];
CGSize myStringSize = [aMessage sizeWithFont:textFont
                   constrainedToSize:maximumSize
                       lineBreakMode:NSLineBreakByWordWrapping];

return myStringSize.height;
}

And then can set the ContentSize of Scrollview accordingly.

Upvotes: 1

Greg
Greg

Reputation: 25459

UITextView is a subclass of UIScrollView and you should use content size after you set up a text to get the size:

self.articleUITextView.text = @"YOUR TEXT";
CGRect rec = self.articleUITextView.frame;
rec.size.height = self.articleUITextView.contentSize.height;
textView.frame = rec;

After that you can just chance contentSize of your scroll view. If you want to use sizeWithFont: it works fine for UILabels but not necessary with UITextView.

Upvotes: 1

Venk
Venk

Reputation: 5955

Try like this,

[self.scrollerArticle setContentSize:CGSizeMake(320, CGRectGetMaxY(self.articleUITextView.frame))];

Upvotes: 4

Related Questions