简体   繁体   中英

UITextView contentSize automatically decreases

I have a UITextView whose height I am trying to resize as the number of lines increases. Apart form this, I need to resize the UIView in which the UITextView is contained. I am using the following code for this:

-(void) textViewDidChange:(UITextView *)textView{

 CGFloat before = textView.frame.size.height; CGRect frame = textView.frame; frame.size = textView.contentSize; CGFloat after = frame.size.height, diff = after - before, final = 0; if (diff>16) { final = 8; }else if(diff<-1){ final = -16; }else{ final = 0; } [self.containerView setFrame: CGRectMake(self.containerView.frame.origin.x, 

self.containerView.frame.origin.y-final, self.containerView.frame.size.width, frame.size.height+13)];

 [textView setFrame: frame]; 

}

I am also trying to change the Y-position of the container as the text is changed. I am using static number values according to font size to avoid complications.

But the problem is that whenever the UITextView enters a new line, it resizes its contentSize to the original size and so the frame of the UITextView is also reduced for a moment, which looks really ugly. Also, the Y-position depends on this contentSize change and it gets all messed up when this automatic resize happens.

I am looking for the same behaviour which apps like whatsapp or viber have. Any idea how I can achieve this?

If I understand correctly, the containerView includes a textfield and must be drawn around it, regardless of the size of the textfield? If that is, try something like this

-(void) textViewDidChange:(UITextView *)textView

{

CGRect frame = textView.frame;

frame.size = textView.contentSize;

//do your magic calculations

[textView setFrame: frame];

[self.containerView setFrame: CGRectMake(self.containerView.frame.origin.x,
self.containerView.frame.origin.y-final, self.containerView.frame.size.width, frame.size.origin.y +frame.size.height+13)];

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM