forEach auto layout Constraints not appearing

My swifts code which uses a for loop to display to imageviews. Right now the code builds but nothing appears. I know I have to move the leading anchor constraint over .25 for the second box. But I would think the first box which is box1 would appear but again nothing is appearing and i dont know why. I haave added a photo of my desired output.

import UIKit

class ViewController: UIViewController {
    var box1 = UIButton();var box2 = UIButton();var box3 = UIImageView()
    override func viewDidLoad() {
        super.viewDidLoad()
            
        [box1,box2,box3].forEach{
            view.addSubview($0)
            $0.backgroundColor = .red
            $0.translatesAutoresizingMaskIntoConstraints = false
            
            
            $0.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: CGFloat(smith)).isActive = true
            $0.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 15).isActive = true

            $0.heightAnchor.constraint(equalToConstant: 30).isActive = true
            $0.widthAnchor.constraint(equalToConstant: 30).isActive = true
            

        }
    }
    
    
}

6L5B2

You need to have the constraints in relation to the last box, so set the constraints for Box1 and then set them for 1, 2 and 3 relatively.

Alternatively have a lookat snapkit, it is a wonderfully easy way to set up constraints

This topic was automatically closed after 166 days. New replies are no longer allowed.