Kelson Hartle
Kelson Hartle

Reputation: 67

Using 5 UIlabels to create 5 stars to mimic a rating system

private let componentDimension: CGFloat = 40.0
private let componentCount: CGFloat = 5.0
private let componentActiveColor = UIColor.black
private let componentInactiveColor = UIColor.gray
func setup() {

        //create 5 labels using for loop and store in array ///figure out how to add a number to it to identify

        //creating custom control, using constraints, using a little bit of animation, uitextfielddelegate

        for _ in 1...5 {

            let label = UILabel()
            addSubview(label)

            for i in 0..<starArray.count {
                           starArray[i].tag = i
                       }

            label.frame = label.frame.offsetBy(dx: 8.0, dy: 0)
            label.frame.size = CGSize(width: componentDimension, height: componentDimension)

            label.font = UIFont(name: "System", size: 32.0)
            label.text = "✭"

            if label.tag == 0 {
                label.textColor = componentActiveColor
            } else {
                label.textColor = componentInactiveColor
            }

            starArray.append(label)
        }
    }

I am trying to create 5 labels that are equally spaced in a custom view. But I am unaware of how to equally space the labels in order to achieve that.

Upvotes: 0

Views: 186

Answers (1)

Jawad Ali
Jawad Ali

Reputation: 14417

Here is a complete class code with stackView Starting point for you

import UIKit

class ViewController: UIViewController {

    private lazy var stackView : UIStackView = {
        let stack = UIStackView()
        stack.axis = .horizontal
        stack.spacing = 10
        stack.distribution = .fillEqually
        stack.alignment = .fill
        stack.translatesAutoresizingMaskIntoConstraints = false
        return stack
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        setUpCostraints()

        for _ in 1...5 {

            let label = UILabel()
            label.font = UIFont.boldSystemFont(ofSize: 30)
            label.text = "✭"

            if label.tag == 0 {
                label.textColor = .red
            } else {
                label.textColor = .blue
            }

            stackView.addArrangedSubview(label)

        }
    }

    override func viewDidLayoutSubviews() {

    }
    func setUpCostraints() {
        view.addSubview(stackView)

        stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        stackView.heightAnchor.constraint(equalToConstant: 50).isActive = true
        stackView.widthAnchor.constraint(equalToConstant: 200).isActive = true
    }


}

enter image description here

Upvotes: 2

Related Questions