我以编程方式向NSWindow的内容视图添加一个按钮,当我添加一个约束来居中时,按钮不会移动,而是缩小窗口:
windowN=NSWindow(contentRect: NSMakeRect((NSScreen.mainScreen()!.visibleFrame.width/2)-100, (NSScreen.mainScreen()!.visibleFrame.height/2)-100, 200, 200), styleMask: NSTitledWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask, backing: NSBackingStoreType.Buffered, `defer`: false, screen: NSScreen.mainScreen())
windowN.releasedWhenClosed=false
windowN.makeKeyAndOrderFront(self)
windowN.title="Title"
windowN.minSize=NSSize(width: 100, height: 100)
let s=NSStoryboard(name: "Storyboard", bundle: NSBundle.mainBundle())
windowN.contentView?=(s.instantiateControllerWithIdentifier("Me") as! NSViewController).view
var view=windowN.contentView!
button=NSButton(frame: NSMakeRect(0,0,100,30))
button.setButtonType(NSButtonType.MomentaryPushInButton)
button.bezelStyle=NSBezelStyle.RoundedBezelStyle
button.title="Hello"
view.addSubview(button)
view.addConstraint(NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: button, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
windowN.delegate=self
不会抛出任何错误。
谢谢,
答案 0 :(得分:0)
来自文档:
默认情况下,视图上的自动调整遮罩会产生约束 完全确定视图的位置。做任何有趣的事情 有了约束,你需要关闭它。 IB将关闭它。
您需要关闭自动调整遮罩:
button.translatesAutoresizingMaskIntoConstraints = false