我在Playground中使用Xcode 8和Swift 3创建了以下代码。根据我所阅读的内容,看起来这应该在中心显示一个大小为30 x 30点的子视图包含UIView。我也试过各种其他类型的约束无济于事。内部UIView只是不显示。
这应该是自定义UIView子类的一部分,使用@IBDesignable和@IBInspectable。如果我手动为子视图设置框架,它们可以正常工作,但我希望可以根据需要自动调整大小。我在这里看到了一些使用视觉格式语言的其他例子,虽然我也没有运气,我想我更喜欢使用锚点。关于为什么这不起作用的任何线索?
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
答案 0 :(得分:1)
用
替换两个setNeedsDisplay()调用 outer.layoutIfNeeded()