Reputation: 9273
i want change the UITextView programmatically with the amount of text i set, and i have a problem, if i add a the UITextView with interface builder and i do this:
CGRect frame = textViewA1.frame;
frame.size.height = textViewA1.contentSize.height;
textViewA1.frame = frame;
all work fine, but if i create the UITextView programmatically, the height don't change, i do this:
UITextView *textViewA1 = [[UITextView alloc] initWithFrame:CGRectMake(5, 5, 320, 50)];
[textViewA1 setFont:[UIFont fontWithName:@"Enriqueta" size:15]];
[textViewA1 setScrollEnabled:NO];
[textViewA1 setUserInteractionEnabled:NO];
[textViewA1 setBackgroundColor:[UIColor clearColor]];
[textViewA1 setText:@"A lot of text"];
CGRect frame = textViewA1.frame;
frame.size.height = textViewA1.contentSize.height;
textViewA1.frame = frame;
in this way the height size of the uitextview don't change, how i can do?
Upvotes: 8
Views: 24990
Reputation: 23271
to scroll UITextView
when added multiple line in textview
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
CGRect frameTextView = textView.frame;
frameTextView.height -= KEY_BOARD_HEIGHT;
textView.frame = frameTextView;
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView;
{
CGRect frameTextView = textView.frame;
frameTextView.height += KEY_BOARD_HEIGHT;
textView.frame = frameTextView;
}
Upvotes: -2
Reputation: 532
i think you need to do :
CGRect frame = textViewA1.frame;
frame.size.height = textViewA1.contentSize.height;
textViewA1.frame = frame;
after the addsubview:
[self.view addSubview: self.textView];
Upvotes: 10
Reputation: 385540
Just send the sizeToFit
message to the UITextView
. It will adjust its own height to just fit its text. It will not change its own width or origin.
[textViewA1 sizeToFit];
Upvotes: 10
Reputation: 7065
Try this code
UIFont * font = [UIFont fontWithName:@"Enriqueta" size:15];
textViewA1.font = font;
NSString * theText = @"A lot of text";
CGSize theStringSize = [theText sizeWithFont:font constrainedToSize:CGSizeMake(190, 1000000) lineBreakMode:UILineBreakModeWordWrap];
CGRect frame = textViewA1.frame;
frame.size.height = theStringSize.height;
textViewA1.frame = frame;
This of course has a static width of 190 pixels for the textview. You can obviously change that!!!
Upvotes: 0
Reputation: 2495
You need to calculate the frame size for the text you have, for instance:
UIFont *font = [UIFont fontWithName:@"Enriqueta" size:15];
NSString *text = @"A lot of text";
CGSize frameSize = [text sizeWithFont:font];
CGRect originalFrame = textViewA1.frame;
textViewA1.frame = CGRectMake(CGRectGetMinX(originalFrame), CGRectGetMinY(originalFrame), frameSize.width, frameSize.height);
To keep it from exceeding a particular height, use:
CGFloat maxHeight = 100; // or something
CGSize frameSize = [text sizeWithFont:font constrainedToSize:maxHeight];
Upvotes: 0