简体   繁体   English

如何使用超级视图自动调整子视图的大小?

[英]How to make a subview automatically resize with its superview?

I have a view which contains one sub-view; 我有一个包含一个子视图的视图; this sub-view itself contains another sub-view, which is meant to be slightly smaller than its superview. 这个子视图本身包含另一个子视图,它意味着比它的superview略小。

I am creating the first subview full-screen size then shrinking it to a very small size on the screen. 我正在创建第一个子视图全屏尺寸,然后将其缩小到屏幕上的非常小的尺寸。 When the subview is tapped, I animate it from its small size to full-screen. 点击子视图时,我会将其从小尺寸设置为全屏幕。

The problem is that my second subview never resizes itself during this animation - it is always rendered full-size and overflows the bounds of its superview. 问题是我的第二个子视图在这个动画期间从不调整自身大小 - 它总是呈现为全尺寸并溢出其超视图的边界。

Is there a simple way to get a subview to keep itself sized proportionally as its superview changes size? 是否有一种简单的方法可以让子视图在其superview更改大小时按比例保持自己的大小?

you could add the autoresizing-behavior programmatically 您可以以编程方式添加自动调整行为

Objective-C Objective-C的

subview.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

Swift 3.x Swift 3.x

subview.autoresizingMask = [.flexibleWidth, .flexibleHeight]

Swift 2.x Swift 2.x

subview.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]

In Interface-Builder navigate to tab 3 and click on the arrows in the middle ;D 在Interface-Builder中,导航到选项卡3,然后单击中间的箭头; D.

Another workaround could be to implement the setFrame-method and always adapt it to the size of the superview (not the given frame.size). 另一种解决方法可能是实现setFrame方法并始终使其适应superview的大小(而不是给定的frame.size)。 Don't forget to set up the origin as you need it. 不要忘记根据需要设置原点。

- (void) setFrame:(CGRect)frame
{
    CGRect rect = self.superview.frame;
    rect.origin.x = 0;
    rect.origin.y = 0;
    [super setFrame:rect];
}

这对我有用

subview.frame = subview.superview.bounds;

If you're using only [.flexibleWidth, .flexibleHeight] for your autoresizing mask, your subview will not get resized proportionally. 如果您仅使用[.flexibleWidth,.flexibleHeight]作为自动调整遮罩,则子视图将不会按比例调整大小。 The right answer is: 正确的答案是:

autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleTopMargin, .flexibleLeftMargin, .flexibleBottomMargin, .flexibleRightMargin]

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

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