Avatar ·

How to programmatically add Auto Layout constraints in Swift?

Hello everyone! I'm a beginner in iOS development and trying to figure out how to layout screens programmatically, without using Storyboard. I've read that for responsiveness you need to use Auto Layout, but I can't understand how to properly add constraints through code.

\n\n

Here's a simple example: I want to place a blue view (UIView) in the center of the screen, with 20 pixel margins from the left and right edges, and a height of 200 points. I create the view and add it to the screen, but it doesn't display or displays incorrectly.

\n\n
import UIKit\n\nclass ViewController: UIViewController {\n    override func viewDidLoad() {\n        super.viewDidLoad()\n        \n        let myView = UIView()\n        myView.backgroundColor = .blue\n        myView.translatesAutoresizingMaskIntoConstrain