我有一个包含两个标签,并在堆栈行一个简单的类:为什么sizeThatFits不能与UILabel一起使用?
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'的框架。所以给定一个未知的框架大小的内部,你如何确定正确的帧大小来包含所有这些?你不能。 – TNguyen
那么在sizeThatFits中指定* width *和a * height *有什么意义?如果我只是指定一个,那就不明确了。即使我在sizeThatFits调用之前添加了如下内容:v.frame = CGRect(x:0,y:0,width:columnWidth,height:100),结果也是一样的。 – GoldenJoe