Search code examples
swiftcocoansviewnsviewcontrollerxcode10.2

Cocoa Swift: Subview not resizing with superview


I'm adding a subview(NSView), here is my code:

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)
}

And it works fine

enter image description here But when I resize the window the subview is not resizing.

enter image description here

Any of you knows why or how can make the subview resize with superview?

I'll really appreciate your help


Solution

  • You set view.autoresizesSubviews to true, which tells view to resize each of its subviews. But you also have to specify how you want each subview to be resized. You do that by setting the subview's autoresizingMask. Since you want the subview's frame to continue to match the superview's bounds, you want the subview's width and height to be flexible, and you want its X and Y margins to be fixed (at zero). Thus:

    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)
    }