iosswiftcustom-button

How to draw multiple horizontally circles in rectangle (UIButton or UIControl) Swift iOS


How to draw about three circle in horizontally area with main and ring color in rectangle. I need to create custom button with this circles, something like this:

enter image description here

Is there any good way to do this?


Solution

  • We can design such kind of views with UIStackView in very ease manner. Take a stackView, set its alignment to center, axis to horizontal and distribution to fill. Create a UILabel/UIButton/UIImageView or even UIView and add rounded radius and border to it. Finally, add those views to the main stackView. Try this.

    override func viewDidLoad() {
        super.viewDidLoad()
    
        //Setup stackView
        let myStackView = UIStackView()
        myStackView.axis = .horizontal
        myStackView.alignment = .center
        myStackView.distribution = .fillEqually
        myStackView.spacing = 8
        view.addSubview(myStackView)
    
        //Setup circles
        let circle_1 = circleLabel()
        let circle_2 = circleLabel()
        let circle_3 = circleLabel()
    
        myStackView.addArrangedSubview(circle_1)
        myStackView.addArrangedSubview(circle_2)
        myStackView.addArrangedSubview(circle_3)
    
        myStackView.translatesAutoresizingMaskIntoConstraints = false
        myStackView.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0.0).isActive = true
        myStackView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 0.0).isActive = true
    }
    
    func circleLabel() -> UILabel {
    
        let label = UILabel()
        label.backgroundColor = UIColor.red
        label.layer.cornerRadius = 12.5
        label.layer.masksToBounds = true
        label.layer.borderColor = UIColor.orange.cgColor
        label.layer.borderWidth = 3.0
    
        label.widthAnchor.constraint(equalToConstant: 25.0).isActive = true
        label.heightAnchor.constraint(equalToConstant: 25.0).isActive = true
    
        return label
    }
    

    enter image description here