Cocoa Swift: Subview not resizing with superview
Asked Answered
W

2

5

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

Westmorland answered 26/4, 2019 at 21:28 Comment(5)
you may need to set the autolayout bounds or create a function to update the subview bounds in viewDidLayoutSubviewsSoma
@jessi, can you post an code example ?Westmorland
If you are using the Interface builder, set constraints between the subview and the newview to be the same (you can do this by anchoring the edges or by anchoring the h and w). Programmatically, I won't reinvent the wheel here - see examples from this SO #26181322Soma
@Soma those examples in the link you mention is just adding constraints but doesn't help if the super view is been resizeWestmorland
I don't understand. As long as the view constraints are related to the superview constraints and you call layoutifneeded, any changes in the superview should cascade to its subview(s)Soma
M
6

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)
}
Misrule answered 29/4, 2019 at 17:28 Comment(0)
W
1

I found a fix for this issue:

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

    }
Westmorland answered 29/4, 2019 at 16:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.