我有几个用例,我需要以编程方式添加标签和"容器"视图(例如UIView)到StackViews和其他控件。
我无法获得要渲染的标签,我确信这是一个简单的布局标志,我忽略了设置。
下面的示例:使用UIView.addSubview()以编程方式呈现UILabel
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)
}
}
以下代码块有效,但没有利用Autolayout。任何帮助将不胜感激。
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)
}
}
答案 0 :(得分:4)
想出来......
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)
}
}