【问题标题】:Cocoa Swift: Subview not resizing with superviewCocoa Swift:子视图不使用超级视图调整大小
【发布时间】:2019-04-26 21:28:49
【问题描述】:

我正在添加一个子视图(NSView),这是我的代码:

override func viewDidAppear() {
    self.view.needsDisplay = true
    let newView = NSView()
    newView.autoresizesSubviews = true
    newView.frame = view.bounds
    newView.wantsLayer = true
    newView.layer?.backgroundColor = NSColor.green.cgColor
    view.addSubview(newView)
}

而且效果很好

但是当我调整窗口大小时,子视图没有调整大小。

你们中的任何人都知道为什么或如何使子视图与父视图一起调整大小吗?

非常感谢您的帮助

【问题讨论】:

  • 您可能需要设置自动布局边界或创建一个函数来更新viewDidLayoutSubviews中的子视图边界
  • @jessi,你能发布一个代码示例吗?
  • 如果您使用界面生成器,请将子视图和新视图之间的约束设置为相同(您可以通过锚定边缘或锚定 h 和 w 来做到这一点)。以编程方式,我不会在这里重新发明轮子 - 请参阅此 SO stackoverflow.com/questions/26180822/… 中的示例
  • @jessi 您提到的链接中的那些示例只是添加约束,但如果超级视图被调整大小则无济于事
  • 我不明白。只要视图约束与父视图约束相关并且您调用 layoutifneeded,父视图中的任何更改都应该级联到其子视图

标签: swift cocoa nsview nsviewcontroller xcode10.2


【解决方案1】:

您将view.autoresizesSubviews 设置为true,这告诉view 调整其每个子视图的大小。但是您还必须指定如何调整每个子视图的大小。您可以通过设置子视图的autoresizingMask 来做到这一点。由于您希望子视图的frame 继续匹配父视图的bounds,因此您希望子视图的widthheight 具有灵活性,并且您希望它的X 和Y 边距固定(为零)。因此:

override func viewDidAppear() {
    self.view.needsDisplay = true
    let newView = NSView()

    // The following line had no effect on the layout of newView in view,
    // so I have commented it out.
    // newView.autoresizesSubviews = true

    newView.frame = view.bounds

    // The following line tells view to resize newView so that newView.frame
    // stays equal to view.bounds.
    newView.autoresizingMask = [.width, .height]

    newView.wantsLayer = true
    newView.layer?.backgroundColor = NSColor.green.cgColor
    view.addSubview(newView)
}

【讨论】:

    【解决方案2】:

    我找到了解决此问题的方法:

    override func viewWillLayout() {
            super.viewWillLayout()
            newView.frame = view.bounds
    
        }
    

    【讨论】:

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