如何用UITextview增加视图大小?
我做了一个示例演示,当我在UITextview
上UITextview
它将扩展,但视图不会展开,这是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约束像
创build一个约束你的myview高约束的NSLayoutConstraint
输出:
这里
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的视图。