ios - 以编程方式使用 addSubview 时,Swift 3 UIView 不呈现 UILabel
<p><p>我有几个用例,我需要以编程方式将标签和“容器” View (例如 UIView)添加到 StackView 和其他控件。 </p>
<p>我无法让标签呈现,我确信这是一个我忽略设置的简单布局标志。</p>
<p>以下示例:使用 UIView.addSubview() 以编程方式呈现 UILabel</p>
<pre><code>import UIKit
class TestViewController: UIViewController {
var label = UILabel()
var container = UIView()
open override func viewDidLoad() {
super.viewDidLoad()
container = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
label.text = "Hello World!"
label.textColor = .white
container.addSubview(label)// <- This does not work
self.view.addSubview(container)
}
}
</code></pre>
<p>以下代码块有效,但没有利用自动布局。如有任何帮助,我们将不胜感激。</p>
<pre><code>import UIKit
class TestViewController: UIViewController {
var label = UILabel()
var container = UIView()
open override func viewDidLoad() {
super.viewDidLoad()
container = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
label.text = "Hello World!"
label.textColor = .white
container.layout(label).topLeft() // <- This works
self.view.addSubview(container)
}
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>想通了...</p>
<pre><code>import UIKit
class TestViewController: UIViewController {
var label = UILabel()
var container = UIView()
open override func viewDidLoad() {
super.viewDidLoad()
container = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
label.text = "Hello World!"
label.textColor = .white
label.frame = container.frame
container.addSubview(label)
self.view.addSubview(container)
}
}
</code></pre></p>
<p style="font-size: 20px;">关于ios - 以编程方式使用 addSubview 时,Swift 3 UIView 不呈现 UILabel,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/43075832/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/43075832/
</a>
</p>
页:
[1]