我做了一个示例演示,当我在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
未展开。
答案 0 :(得分:1)
声明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约束
创建约束你的myview hight约束的NSLayoutConstraint
输出:
答案 1 :(得分:0)
1.将视图约束设置为“前导”,“尾随”,“底部”并修复它的高度,并将高度约束的出口设为 viewHeightConstraint 。
2.UITextView从superview(UIView)到Leading,Trailing,Bottom和Top的约束。
3.在UCextview的shouldChangeTextInRange委托中使用以下方法获取字符串高度
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;
答案 2 :(得分:0)
根据我的经验,您必须将最高约束设置为评论视图&设置评论的优先级查看(低: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];
}
输出
希望这可以帮助您设置可调整大小的视图。