how to center a view in swift

To center a UIView in Swift using AutoLayout, you can use the following code:

main.swift
// Create the view to be centered
let myView = UIView()

// Add the view to the parent view
self.view.addSubview(myView)

// Set the view's translatesAutoresizingMaskIntoConstraints property to false
myView.translatesAutoresizingMaskIntoConstraints = false

// Create autolayout constraints to center the view horizontally and vertically
let horizontalConstraint = NSLayoutConstraint(item: myView, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0)
let verticalConstraint = NSLayoutConstraint(item: myView, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1, constant: 0)

// Add the constraints to the parent view
self.view.addConstraints([horizontalConstraint, verticalConstraint])
784 chars
16 lines

This code creates a new UIView called myView, adds it to the parent view, and sets its translatesAutoresizingMaskIntoConstraints property to false to enable AutoLayout constraints. It then creates two constraints using the NSLayoutConstraint class to center the view horizontally and vertically within the parent view. Finally, the constraints are added to the parent view using the addConstraints method.

gistlibby LogSnag