简体   繁体   中英

Swift: Resize Embedded Custom NSView

I have a custom NSView that is embedded in a NSScrollView.

I have set the custom view to use a different view controller.

import Cocoa

class ViewController: NSViewController
{

    @IBOutlet weak var clipView: NSClipView!
    var vc : NSViewController?

    override func viewDidLoad()
    {
        super.viewDidLoad()
        if let storyboard = NSStoryboard(name: "Main",bundle: nil)
        {
            vc = storyboard.instantiateControllerWithIdentifier("vc") as? NSViewController
            clipView.documentView = vc!.view
        }
    }
}

This all seems to work, but I want the view controller in custom view to grow when I resize my outer window.

I have set constraints and the custom view grows accordingly, but the content says the same width.

在此处输入图片说明

When the window is expanded the custom frame changes size but its contents do not resize. For instance I'd like the button in this case to stay right aligned in the view.

在此处输入图片说明

As you can see the red background of the custom view changes size when the window expands, but the button remains in its original location.

How do I get the inner view to resize with the outer view?

UPDATE: Have followed the suggestions below. I've added an NSScrollView now and with all constraints it follows the resize beautifully. When I remove the bottom constraint it collapses in on itself and is bottom aligned:

在此处输入图片说明

I guess I need to specify a height and to top align the view. Any ideas?

If you set a background on the view itself, you can see that its size/position doesn't change.

vc.view.wantsLayer = true
vc.view.layer?.backgroundColor = NSColor.blueColor().CGColor

例

So you can add constraints telling it to fill the whole clip view:

vc.view.translatesAutoresizingMaskIntoConstraints = false

// these are 10.11-only APIs, but you can use the visual format language or any other autolayout APIs
vc.view.leadingAnchor.constraintEqualToAnchor(vc.view.superview!.leadingAnchor).active = true
vc.view.topAnchor.constraintEqualToAnchor(vc.view.superview!.topAnchor).active = true
vc.view.bottomAnchor.constraintEqualToAnchor(vc.view.superview!.bottomAnchor).active = true
vc.view.trailingAnchor.constraintEqualToAnchor(vc.view.superview!.trailingAnchor).active = true

固定版

But then I would ask, why are you using a scroll view at all?

假设外部视图约束更改后,您在按钮中具有正确的约束,则可能要调用view.layoutIfNeeded()或button.layoutIfNeeded()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM