【发布时间】:2018-03-09 07:02:26
【问题描述】:
我有一个简单的类,它在堆栈中包含两个标签和一行:
class TestView: UIView
{
let label_A = UILabel()
let label_B = UILabel()
override init(frame: CGRect) { super.init(frame: frame); setup() }
required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); setup() }
func setup()
{
let view_BG = UIView()
let view_LineH = UIView()
// Configure
view_BG.backgroundColor = .white
view_BG.layer.cornerRadius = 6
view_LineH.backgroundColor = .gray
label_A.numberOfLines = 0
label_A.backgroundColor = UIColor(red: 1, green: 0, blue: 0, alpha: 0.2)
label_A.textColor = .red
label_B.numberOfLines = 0
label_B.textColor = .blue
label_B.backgroundColor = UIColor(red: 0, green: 0, blue: 1, alpha: 0.2)
label_A.text = "TestA"
label_B.text = "Experiment with Swift standard library types and learn high-level concepts using visualizations and practical examples. Learn how the Swift standard library uses protocols and generics to express powerful constraints. Download the playground below to get started."
// Assemble
self.addSubview(view_BG)
view_BG.addSubview(label_A)
view_BG.addSubview(view_LineH)
view_BG.addSubview(label_B)
// Layout
view_BG.constrain_edges(to: self)
label_A.constrain_edges(to: view_BG, excludingEdge: .bottom)
label_B.constrain_edges(to: view_BG, excludingEdge: .top)
view_LineH.constrain_height(1)
view_LineH.constrain_left(to: view_BG)
view_LineH.constrain_right(to: view_BG)
view_LineH.constrain_topToBottom(of: label_A)
label_B.constrain_topToBottom(of: view_LineH)
}
}
当我调用 sizeThatFits 时,它只会向我吐出高度:
let v = TestView()
let s = v.sizeThatFits(CGSize(width: 200, height: 10000))
// s is (200, 10000)
如何计算给定宽度的所需高度?
【问题讨论】:
-
它给你回报是有道理的。
TestView中的所有约束都被约束到边缘。但是你还没有设置TestView的框架。因此,给定内部所有内容的未知帧大小,您如何确定包含所有内容的正确帧大小?你不能。 -
那么在sizeThatFits中指定一个width和一个height有什么意义呢?如果我只指定一个,那将是模棱两可的。即使我在 sizeThatFits 调用之前添加类似: v.frame = CGRect(x: 0, y: 0, width: columnWidth, height: 100) ,结果也是一样的。
标签: ios swift uiview autolayout uilabel