【发布时间】:2020-04-21 10:02:49
【问题描述】:
我想以编程方式在我的视图控制器中添加一个视图并集中它。我将视图作为子视图添加到父视图并启用自动布局但它没有显示。
import UIKit
class ViewController: UIViewController {
lazy var newView:UIView = {
let view = UIView()
view.backgroundColor = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)
view.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
return view
}()
let titleLable = UILabel()
let bodyLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(newView)
newView.translatesAutoresizingMaskIntoConstraints = false
newView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
newView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
}
}
【问题讨论】:
-
您应该使用基于框架的布局或自动布局。不是都。如果您想使用自动布局,则应按照 Roman 在答案中的建议进行操作。
标签: ios swift autolayout