create 5 boxes of rainbow colors in swift

To create 5 boxes of rainbow colors in Swift, you can use a UIStackView to hold 5 UIView objects that have a different background color. Here's an example:

main.swift
import UIKit

class RainbowViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Create the stack view
        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.alignment = .center
        stackView.distribution = .fillEqually
        stackView.spacing = 10.0
        view.addSubview(stackView)
        
        // Create the rainbow colors
        let colors: [UIColor] = [.red, .orange, .yellow, .green, .blue]
        
        // Add views to the stack view
        for color in colors {
            let boxView = UIView()
            boxView.backgroundColor = color
            stackView.addArrangedSubview(boxView)
        }
        
        // Set the constraints
        stackView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            stackView.widthAnchor.constraint(equalToConstant: 250.0),
            stackView.heightAnchor.constraint(equalToConstant: 50.0)
        ])
    }
    
}
1196 chars
37 lines

In this code, we created a UIStackView with a horizontal axis, centered alignment, and equal distribution of the arranged subviews. We specified a spacing of 10 points between each subview.

Next, we created an array of UIColor objects with the colors of the rainbow. We then looped through this array and created a UIView with each color as its background color. We added each of these views to the stack view with the addArrangedSubview method.

Finally, we added constraints to the stack view to center it in the view controller's view with a fixed width and height. This ensures that our rainbow boxes will be centered and sized correctly on any device.

related categories

gistlibby LogSnag