create a uiview with a red background color and set it’s centerxanchor to another uiview with blue background color in swift

To create a UIView with a red background color and set its centerXAnchor to another UIView with blue background color in Swift, you can follow these steps:

main.swift
// Create the red view
let redView = UIView()
redView.backgroundColor = .red
redView.translatesAutoresizingMaskIntoConstraints = false // enable AutoLayout

// Add the red view to the superview
view.addSubview(redView)

// Create the blue view
let blueView = UIView()
blueView.backgroundColor = .blue
blueView.translatesAutoresizingMaskIntoConstraints = false // enable AutoLayout

// Add the blue view to the superview
view.addSubview(blueView)

// Add the center x anchor constraint from the red view to the blue view
redView.centerXAnchor.constraint(equalTo: blueView.centerXAnchor).isActive = true
602 chars
19 lines

This code creates a red UIView with translatesAutoresizingMaskIntoConstraints set to false to enable AutoLayout. We then add the red UIView to the superview. We create a blue UIView with translatesAutoresizingMaskIntoConstraints set to false to enable AutoLayout and add it to the superview as well. Finally, we use the centerXAnchor.constraint(equalTo:) method to add a center X anchor constraint from the red view to the blue view. This ensures that the red view is horizontally centered with respect to the blue view.

gistlibby LogSnag