Search code examples
swiftfor-loopheightwidthnslayoutconstraint

create loop to constraint width and height objects


What I want to do is create a loop that allows pic and slide to have the same width and height constraints. Since I am constraining 0.25 to all constraints. I assume there is a way to do this without have to write all 4 lines of this code.

NSLayoutConstraint.activate([
  pic.heightAnchor.constraint(equalToConstant: 0.25),
  pic.widthAnchor.constraint(equalToConstant: 0.25),

  slide.heightAnchor.constraint(equalToConstant: 0.25),
  slide.widthAnchor.constraint(equalToConstant: 0.25),
])

Solution

  • You can do

    [pic,slide].forEach {  
        $0.heightAnchor.constraint(equalToConstant: 0.25).isActive = true
        $0.widthAnchor.constraint(equalToConstant: 0.25).isActive = true
    }