简体   繁体   English

如何使UIView扩展为包含具有自动布局和IB的UIImageView或UITextView?

[英]How to make a UIView expand to contain a UIImageView or a UITextView with auto layout and IB?

I have a UIView that contains two subviews - a UIImageView or a UITextView. 我有一个包含两个子视图的UIView-UIImageView或UITextView。 The UIImageView has a fixed height and width. UIImageView具有固定的高度和宽度。 The UITextView has variable size. UITextView具有可变大小。

Only one of the UIImageView and UITextView would be displayed at a time. 一次仅显示UIImageView和UITextView中的一个。 I plan to accomplish this programmatically by setting hidden = YES . 我计划通过设置hidden = YES来以编程方式完成此任务。

I would like the UIView to hug whichever child view is not hidden with no margin. 我希望UIView能够拥抱没有隐藏的任何子视图。

I would like to accomplish this with IB and autolayout if possible because the rest of the view is built this way. 如果可能的话,我想使用IB和自动布局来完成此操作,因为视图的其余部分都是以此方式构建的。

So far I have created constraints that link the 4 edges of both of the subviews to the parent view and constraints for the height and width of the UIImageView. 到目前为止,我已经创建了将两个子视图的4条边链接到父视图的约束,以及UIImageView的高度和宽度的约束。 Naturally this creates a content priority ambiguity. 自然,这会造成内容优先级的歧义。

I would appreciate any advice. 我将不胜感激任何建议。

Thank you! 谢谢!

So the contain view has to have trailing constraint and constraint with bottom which should have IBOutlet(s) references in viewcontroller and then when the text changes : 因此,包含视图必须具有尾随约束和底部约束,这些约束应在viewcontroller中具有IBOutlet引用,然后在文本更改时具有:

- (void)textViewDidChange:(UITextView *)textView { 
    [self.textView sizeToFit];
    self.containerViewTrailingConstraint.constant = self.textView.contentSize.width; 
    self.containerViewConstraintWithBottom.constant = self.textView.contentSize.height; 
    [self.view layoutIfNeeded];
}

And when the textView is hidden then you have to set the self.containerViewTrailingConstraint.constant, self.containerViewConstraintWithBottom.constant in relation with the imageView 并且当textView隐藏时,您必须相对于imageView设置self.containerViewTrailingConstraint.constant,self.containerViewConstraintWithBottom.constant

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM