I want to add a view in my view controller programmatically and centralise it. I added the view as subview to the parent view and enable autolayout yet its not showing.
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
}
}
Size constraints are missing for newView
. You removed them with newView.translatesAutoresizingMaskIntoConstraints = false
. To restore all required constraints add the lines below to viewDidLoad
:
newView.widthAnchor.constraint(equalToConstant: 200).isActive = true
newView.heightAnchor.constraint(equalToConstant: 200).isActive = true