我在其超级视图的函数中创建了一个视图
let black = NSView(frame: NSRect(x: 0, y: 0, width: 10, height: 10))
black.translatesAutoresizingMaskIntoConstraints = false
black.wantsLayer = true
black.layer?.backgroundColor = NSColor.black.cgColor
self.addSubview(black)
black.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -15).isActive = true
black.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 15).isActive = true
black.heightAnchor.constraint(equalToConstant: 115).isActive = true
black.widthAnchor.constraint(equalToConstant: 115).isActive = true
print ("origin (\(black.frame.origin.x),\(black.frame.origin.y)) size (\(black.frame.size.width),\(black.frame.size.height)) ")
输出为origin(0,0)
,size(10,10)
,这些是创建视图的值。
在屏幕上,黑色视图按预期定位origin:(15,15)
size:(115,115)
。
为什么框架没有更新?
答案 0 :(得分:2)
设置约束后,您可以更新视图的框架,调用Cocoa的layoutIfNeeded函数:
black.layoutSubtreeIfNeeded()