【问题标题】:How to resize a UIView to a specific height and width including its subviews?如何将 UIView 的大小调整为特定的高度和宽度,包括其子视图?
【发布时间】:2018-03-09 06:51:54
【问题描述】:

我在尝试正确调整 UIView 大小时遇到​​问题。

下面的示例场景:

// other view controller initializations

let containerView = UIView(frame: CGRect(x:0, y:0, width: self.view.bounds.width, height: self.view.bounds.height))
self.view.addSubview(containerView)
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]

let subView = UIView(frame: CGRect(x:0, y:0, width:containerView.bounds.size.width / 2, height: containerView.bounds.size.height))
containerView.addSubview(subView)
subView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

假设我想将 containerView 调整为特定的高度和宽度,这样子视图也会与 containerView 并行调整自身的大小。

我怎样才能做到这一点?

【问题讨论】:

  • 你可以设置subViews的高度和宽度锚点,而不是在构造函数中指定它
  • 你的错误是什么?上面的代码工作完美。尝试分配两个视图的 backgroundColor 进行测试
  • 最好的办法是自动布局...
  • 你们能举一个例子 sn-p 或这个场景吗?

标签: ios swift uiview resize calayer


【解决方案1】:

别忘了为subView设置以下属性

subView.autoresizesSubviews = true;

根据Apple documentation

一个整数位掩码,用于确定接收器如何调整自身大小 当其父视图的边界发生变化时。

所以使用你的例子,它看起来像这样

let containerView = UIView(frame: CGRect(x:0, 
                                         y:0, 
                                         width: self.view.bounds.width, 
                                         height: self.view.bounds.height))

containerView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.view.addSubview(containerView)

let subView = UIView(frame: CGRect(x:0, 
                                   y:0, 
                                   width: containerView.bounds.size.width / 2, 
                                   height: containerView.bounds.size.height))

subView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
subView.autoresizesSubviews = true;
containerView.addSubview(subView)

【讨论】:

    【解决方案2】:

    我能够通过使用UIStackView 来实现我想要的。

    let stackView = UIStackView(frame: .zero)
    currentPage.addSubview(stackView)
    constraintViewToSuperView(view: stackView) // my helper function to constraint stackview to bounds of parent
    
    stackView.axis = .vertical
    stackView.alignment = .fill
    stackView.distribution = .fillProportionally
    stackView.spacing = 1
    stackView.backgroundColor = .red
    

    关键是将UIStackview 限制在它的父级范围内。然后我对父母所做的任何调整大小也会按比例调整UIStackview 的孩子的大小。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-14
      • 2015-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多