使用自动布局扩展为文本的 UITextView [英] UITextView that expands to text using auto layout

查看:25
本文介绍了使用自动布局扩展为文本的 UITextView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个完全使用自动布局以编程方式布局的视图.我在视图中间有一个 UITextView,上面和下面都有项目.一切正常,但我希望能够在添加文本时扩展 UITextView.随着它的扩展,这应该会将其下方的所有内容向下推.

I have a view that is laid out completely using auto layout programmatically. I have a UITextView in the middle of the view with items above and below it. Everything works fine, but I want to be able to expand UITextView as text is added. This should push everything below it down as it expands.

我知道如何以弹簧和支柱"的方式做到这一点,但是有没有一种自动布局的方式来做到这一点?我能想到的唯一方法是在每次需要增长时移除并重新添加约束.

I know how to do this the "springs and struts" way, but is there an auto layout way of doing this? The only way I can think of is by removing and re-adding the constraint every time it needs to grow.

推荐答案

包含 UITextView 的视图将通过 AutoLayout 使用 setBounds 分配其大小.所以,这就是我所做的.超级视图最初设置了所有其他应有的约束,最后我为 UITextView 的高度设置了一个特殊约束,并将其保存在实例变量中.

The view containing UITextView will be assigned its size with setBounds by AutoLayout. So, this is what I did. The superview is initially set up all the other constraints as they should be, and in the end I put one special constraint for UITextView's height, and I saved it in an instance variable.

_descriptionHeightConstraint = [NSLayoutConstraint constraintWithItem:_descriptionTextView
                                 attribute:NSLayoutAttributeHeight 
                                 relatedBy:NSLayoutRelationEqual 
                                    toItem:nil 
                                 attribute:NSLayoutAttributeNotAnAttribute 
                                multiplier:0.f 
                                 constant:100];

[self addConstraint:_descriptionHeightConstraint];

setBounds 方法中,我更改了常量的值.

In the setBounds method, I then changed the value of the constant.

-(void) setBounds:(CGRect)bounds
{
    [super setBounds:bounds];

    _descriptionTextView.frame = bounds;
    CGSize descriptionSize = _descriptionTextView.contentSize;

    [_descriptionHeightConstraint setConstant:descriptionSize.height];

    [self layoutIfNeeded];
}

这篇关于使用自动布局扩展为文本的 UITextView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆