2016-09-21 58 views
0

我在Playground中使用Xcode 8和Swift 3创建了以下代码。根据我读过的内容,似乎应该显示一个子视图,大小为30 x 30点,位于包含UIView的中心。我也尝试了各种其他类型的约束无济于事。内部UIView只是不显示。以编程方式创建UIView约束,但锚点未应用

这应该是使用@IBDesignable和@IBInspectable的自定义UIView子类的一部分。如果我手动设置子视图的框架,他们工作得很好,但我想要有东西自动调整大小,如果需要的选项。我在这里使用了可视化格式化语言,还看到了其他一些例子,尽管我还没有和他们一起运气,我想我更喜欢使用锚点。任何线索为什么这不起作用?

import UIKit 

// Define a simple UIView to put a subview in 
let outer = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 480)) 

// Add a little style to verify that properties are updating 
outer.layer.borderWidth = 2.0 
outer.layer.borderColor = UIColor.green.cgColor 

// Create a subview 
let inner = UIView(frame: CGRect.zero) 

// I believe this is needed to set constraints manually 
inner.translatesAutoresizingMaskIntoConstraints = false 

// Add the subview. This displays outer, and it's just a box with a border 
outer.addSubview(inner) 

// Add a color so I can see it 
inner.backgroundColor = UIColor.black 

// These constraints should be enough to define the position and size 
inner.heightAnchor.constraint(equalToConstant: 30.0).isActive = true 
inner.widthAnchor.constraint(equalToConstant: 30.0).isActive = true 
inner.centerYAnchor.constraint(equalTo: outer.centerYAnchor).isActive = true 
inner.centerXAnchor.constraint(equalTo: outer.centerXAnchor).isActive = true 

outer.setNeedsDisplay() // This doesn't seem to do anything, but I tried it 
inner.setNeedsDisplay() // Same here 

inner.frame // Shows as {x 0 y 0 w 0 h 0} 

// Show the UIView, which looks exactly the same as before. 
outer 

回答

1

更换两个setNeedsDisplay()与

outer.layoutIfNeeded()

+0

完美要求。非常感谢! –

相关问题