Maurizio
Maurizio

Reputation: 89

TextView autoheight in a ScrollView

I'm trying to insert a TextView inside a Scrollview. The scrollview work but the content of TextView not show complete, because appear their scroll. I would show complete content of TextView without scroll.

enter image description here

file.h

@interface DetailViewController : UIViewController{
IBOutlet UITextView *detailTextView;
IBOutlet UIScrollView *scroller;    
}

@property(retain, nonatomic) IBOutlet UIScrollView *scroller;

-(void)setTextViewForRecipes: (Recipe *)theRecipe;

@end

file.m

@implementation DetailViewController
@synthesize  scroller;

-(void) setTextViewForRecipe:(Recipe *)theRecipe
{
 [detailTextView setText:theRecipe.detail]; 
}

- (void)viewDidLoad {
CGRect frame = detailTextView.frame;
frame.size.height = detailTextView.contentSize.height;
detailTextView.frame = frame;
[scroller setContentSize: CGSizeMake(280, detailTextView.frame.origin.y + detailTextView.frame.size.height + 10)];    
}

Upvotes: 0

Views: 716

Answers (3)

rob mayoff
rob mayoff

Reputation: 386058

You've got the right idea in viewDidLoad by setting detailTextView's frame height to its contentSize height. But you need do that after you set the text of the view, and of course you need to adjust the scroller's contentSize again.

-(void) setTextViewForRecipe:(Recipe *)theRecipe
{
    detailTextView.text = theRecipe.detail;
    CGRect frame = detailTextView.frame;
    frame.size.height = detailTextView.contentSize.height;
    detailTextView.frame = frame;
    scroller.contentSize = CGSizeMake(280, 10 + CGRectGetMaxY(frame));
}

Upvotes: 2

fzwo
fzwo

Reputation: 9902

As bandejapaisa pointed out, it's usually not necessary to wrap a UITextView inside a UIScrollView, because the textView can scroll by itself.

If, however, you really find this necessary, you can find out the size of the text if it were rendered with a certain font:

CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:fontSizeOfYourTextView]
                   constrainedToSize:CGSizeMake(widthOfYourTextView, MAXFLOAT)
                       lineBreakMode:UILineBreakModeOfYourTextView];

This will find out the height. Adapt to your needs, but be warned: This gets a little hackery, and you'll probably need to do some trial and error before you achieve the desired outcome.

Upvotes: 0

bandejapaisa
bandejapaisa

Reputation: 26992

UITextView is a subclass of UIScrollView, so you shouldn't add it to a scroll view.

Upvotes: 0

Related Questions