[英]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: 这是多次调用的代码,并通过不同的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. 我可以得到子视图走动
setFrameOrigin
,但移动他们两个向上或向下基础上,他们错误地定位在开头。
I ended up ditching using constraints and using setFrameSize
on the super view. 我最终使用约束并在超级视图上使用
setFrameSize
了。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.