【问题标题】:Autoresize subviews when resizing the superview调整超级视图大小时自动调整子视图大小
【发布时间】:2016-07-28 11:42:02
【问题描述】:

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

假设我有一个自定义的 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的frame正确调整大小?

谢谢。

【问题讨论】:

    标签: ios objective-c swift uiview uiimageview


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      如果您不使用自动布局,请交换下面的行

      请确保在 self(UIView) 分配后设置框架

      self.frame = CGRectMake(0, 0, width, height)
      self.imageView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight,.FlexibleTopMargin, .FlexibleLeftMargin, .FlexibleRightMargin, .FlexibleBottomMargin]
      addSubview(self.imageView)
      

      【讨论】:

        猜你喜欢
        • 2011-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多