如何用UITextview增加视图大小?

我做了一个示例演示,当我在UITextviewUITextview它将扩展,但视图不会展开,这是UITextview的超级视图。

 - (void)textViewDidChange:(UITextView *)textView { CGFloat fixedWidth = textView.frame.size.width; CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)]; CGRect newFrame = textView.frame; newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height); textView.frame = newFrame; self.myTextView.scrollEnabled = NO; CGRect viewFrame = self.myCommentView.frame; viewFrame.size.height =self.myCommentView.frame.size.height + 1; viewFrame.origin.y=self.myCommentView.frame.origin.y - 1; self.myCommentView.frame =viewFrame; [self.myTextView layoutIfNeeded]; [self.myCommentView layoutIfNeeded]; } 

问题是

视图不扩展与UITextview 。如果视图是扩展UITextview不扩大。

图片

在这里输入图像说明

UITextView约束

在这里输入图像说明

故事板

在这里输入图像说明 UITextview扩展时,我希望两者都应该展开。

在这里输入图像说明 谢谢

声明UITextViewDelegate委托方法。

 @property (strong, nonatomic) IBOutlet UITextView *txtview; @property (strong, nonatomic) IBOutlet NSLayoutConstraint *backgroundviewhight; // myview hight constrain. @property (strong, nonatomic) IBOutlet UIView *myview; _txtview.delegate = self; - (void)textViewDidChange:(UITextView *)textView { CGFloat fixedWidth = textView.frame.size.width; CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)]; CGRect newFrame = textView.frame; newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height); textView.frame = newFrame; self.txtview.scrollEnabled = NO; _backgroundviewhight.constant = newFrame.size.height; [self.txtview layoutIfNeeded]; [self.myview layoutIfNeeded]; } 

你的textview约束像

你的textview约束

创build一个约束你的myview高约束的NSLayoutConstraint

Myview限制

输出:

这里

1.将View约束设置为Leading,Trailing,Bottom并固定其高度,并将高度约束的出口设置为viewHeightConstraint

2.从superview(UIView)的UITextView约束到Leading,Trailing,Bottom和Top。

3.在UITextview的shouldChangeTextInRange委托中使用下面的方法获取string高度

 NSString *finalString = [textView.text stringByReplacingCharactersInRange:range withString:text]; /********** set width in width of your textview and font for your text in font ********/ CGRect rect = [finalString boundingRectWithSize:(CGSize){width , CGFLOAT_MAX} options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:font} context:nil]; /** Now set the height for view as you type it will increase according with textView **/ _viewHeightConstraint.constant = rect.size.height + 30; 

根据我的经验,你必须设置顶部约束来评论视图和设置您的评论视图(低:250),如下所示的优先级。

设置优先级:

在这里输入图像说明

评论视图约束:

在这里输入图像说明

设置TextView约束:

在这里输入图像说明

在你的didTextChange方法中稍作更新:

 - (void)textViewDidChange:(UITextView *)textView { CGFloat fixedWidth = textView.frame.size.width; CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)]; if (newSize.height>textView.frame.size.height) { [textView sizeToFit]; textView.scrollEnabled = NO; } [textView layoutIfNeeded]; [self.myCommentView layoutIfNeeded]; } 

输出:

在这里输入图像说明

希望这将有助于您设置可resize的视图。