为什么自动布局不更改视图框架
Why doesn't Autolayout change a views frame
我在其父视图的函数中创建了一个视图
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)
.
为什么框架没有更新?
设置约束后,您可以调用相同的 layoutIfNeeded 函数更新视图框架 Cocoa:
black.layoutSubtreeIfNeeded()
我在其父视图的函数中创建了一个视图
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)
.
为什么框架没有更新?
设置约束后,您可以调用相同的 layoutIfNeeded 函数更新视图框架 Cocoa:
black.layoutSubtreeIfNeeded()