调整超级视图大小时自动调整子视图

问题描述 投票:2回答:2

我无法正确处理子视图的大小调整:

假设我有一个自定义的UIView类,里面包含一个UIImageView。

最初,我设置了UIViews,如下所示:

// width and height are UIImage width height
// it is possible that the UIImage width height is larger than the container

self.imageView.frame = CGRectMake(0 ,0, width, height)
self.imageView.backgroundColor = UIColor.redColor()
self.imageView.contentMode = UIViewContentMode.ScaleAspectFit
self.imageView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight,.FlexibleTopMargin, .FlexibleLeftMargin, .FlexibleRightMargin, .FlexibleBottomMargin]
addSubview(self.imageView)

self.frame = CGRectMake(0, 0, width, height)
self.backgroundColor = UIColor.greenColor()

我们将这个自定义UIView称为MyView。

然后当我想将这个“myView”放在ViewController中时。我做了以下事情:

myView.frame = CGRectMake(xPos, yPos, 100, 100)
myView.autoResizeSubviews = true

我发现在我这样做之后,我得到了以下结果。 MyView place at the correct place with correct size, but the internal UIImageView got even a smaller size.

为什么会这样?如何根据MyView框架正确调整MyView中的所有子视图?

谢谢。

ios objective-c swift uiview uiimageview
2个回答
2
投票

哦,我发现autoresizing mask应该设置如下:

self.imageView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight, .FlexibleRightMargin, .FlexibleBottomMargin]

这允许锚固定在顶部和左侧,并允许在其他边缘上调整大小。


1
投票

如果您没有使用自动布局,则交换波纹线

请确保您在自我(UIView)分配后设置框架

self.frame = CGRectMake(0, 0, width, height)
self.imageView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight,.FlexibleTopMargin, .FlexibleLeftMargin, .FlexibleRightMargin, .FlexibleBottomMargin]
addSubview(self.imageView)
© www.soinside.com 2019 - 2024. All rights reserved.