UITextView that expands to text using auto layout

前端 未结 16 2040
面向向阳花
面向向阳花 2020-11-28 01:25

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 f

16条回答
  •  迷失自我
    2020-11-28 01:48

    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];
    

    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];
    }
    

提交回复
热议问题