Layout Anchors iOS Tutorial
Layout anchors in a view can be used to autocreate constraints relative to other views. In this tutorial two button will be posiitoned on the main view using layout anchors. This tutorial is made with Xcode 11 and built for iOS 13.
Open Xcode and create a new Single View App.
For product name, use IOSLayoutAnchorTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.
Go to the ViewController.swift file and change the viewDidLoad method to
override func viewDidLoad() { super.viewDidLoad() // 1. let firstButton = UIButton(type: .roundedRect) firstButton.setTitle("First", for: .normal) firstButton.sizeToFit() firstButton.backgroundColor = .green firstButton.tintColor = .black firstButton.translatesAutoresizingMaskIntoConstraints = false view.addSubview(firstButton) // 2. firstButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true firstButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 50).isActive = true // 3. let secondButton = UIButton(type: .roundedRect) secondButton.setTitle("Second", for: .normal) secondButton.sizeToFit() secondButton.backgroundColor = .yellow secondButton.tintColor = .black secondButton.translatesAutoresizingMaskIntoConstraints = false view.addSubview(secondButton) // 4. secondButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true secondButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -100).isActive = true }
an UIButton with a backgroundcolor of green and a title of “First” is added to the main view.
Using the top- and the leading layout anchor the button is positioned 100 point from the top and 5p points to the left of the main view
an UIButton with a backgroundcolor of yellow and a title of “Second” is added to the main view.
Using the bottom- and the centerX layout anchor the button is positioned 100 point from the bottom and at the center of the X axis of the main view.
Build and Run the Project. The 2 buttons are displayed at the correct postion on the main view.
The source code of the IOSLayoutAnchorTutorial can be downloaded at the ioscreator repository on Github.










