简体   繁体   English

UITextView contentSize自动减小

[英]UITextView contentSize automatically decreases

I have a UITextView whose height I am trying to resize as the number of lines increases. 我有一个UITextView ,我尝试随着行数的增加调整其高度。 Apart form this, I need to resize the UIView in which the UITextView is contained. 除此以外,我需要调整其中包含UITextViewUIView大小。 I am using the following code for this: 我为此使用以下代码:

-(void) textViewDidChange:(UITextView *)textView{ -(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)]; 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. 我还尝试随着文本的更改来更改容器的Y位置。 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. 但是问题在于,每当UITextView输入新行时,它都会将contentSize调整为原始大小,因此UITextView的框架也会暂时缩小,这看起来确实很丑。 Also, the Y-position depends on this contentSize change and it gets all messed up when this automatic resize happens. 同样,Y位置取决于此contentSize更改,并且在发生这种自动调整大小时,它会变得一团糟。

I am looking for the same behaviour which apps like whatsapp or viber have. 我正在寻找与whatsapp或viber等应用程序相同的行为。 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? 如果我理解正确,containerView包含一个文本字段,并且无论文本字段的大小如何,都必须在其周围绘制一个文本字段? 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)];

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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