简体   繁体   中英

Center NSView after adding it to the superview with setFrameOrigin in Swift on OSX

I am dynamically adding subviews to a superview during runtime and want to resize the superview to match the subview. The resizing is working fine, but it's not centered when I add the subview. The second view seems to be added where the first one ended.

This is a bit of code that is called multiple times and is passed different subViews:

    self.currentConstraints = [
        NSLayoutConstraint(item: superView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: subView.frame.size.height),
        NSLayoutConstraint(item: superView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: subView.frame.size.width)
    ]

    superView.addConstraints(self.currentConstraints!)

    addChildViewController(viewController)
    superView.addSubview(viewController.view)

I can get the subView to move around with setFrameOrigin , but that moves them both up or down based on where they wrongly positioned in the beginning.

I ended up ditching using constraints and using setFrameSize on the super view. This approach I was skipping before because the popover it was in wasn't resizing, so I just set it as a delegate and had it resize when the new subview was added.

    superView.setFrameSize(subView.frame.size)

    self.delegate.subViewChanged(subView.frame.size)

    addChildViewController(viewController)
    superView.addSubview(viewController.view)

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