Search code examples
iosswift4nslayoutconstraintpreset

how to define preset height and width of object for constraint (Swift4)


My code creates constraints for uitextfields all programatically. And it works. I am trying to optimize my coding practice and try to find a way to use a preset constraint to determine all of the textfields height and width. As you can see both a1. and a2. are the exact same height and width. I wanted to see if there was a way to just call the same height and width for each textfield and stead of just always coding it.

 a1.translatesAutoresizingMaskIntoConstraints = false
    let leadingc2 = a1.widthAnchor.constraint(equalToConstant: 75)
    let trailingC2 = a1.heightAnchor.constraint(equalToConstant: 50)
    let topc2 = a1.centerXAnchor.constraint(equalTo: self.view.centerXAnchor, constant: -60)
    let bottomc2 = a1.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: -275)

    a1t = [leadingc2,trailingC2,topc2,bottomc2]

    NSLayoutConstraint.activate(a1t)

    //

    a2.translatesAutoresizingMaskIntoConstraints = false
    let leadingc22 = a2.widthAnchor.constraint(equalToConstant: 75)
    let trailingC22 = a2.heightAnchor.constraint(equalToConstant: 50)
    let topc22 = a2.centerXAnchor.constraint(equalTo: self.view.centerXAnchor, constant: 60)
    let bottomc22 = a2.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: -275)

    a2t = [leadingc22,trailingC22,topc22,bottomc22]

    NSLayoutConstraint.activate(a2t)

Solution

  •    //Make a variable?
    
       let height = 75
    
    
     //Or you can make a function to shorten the progress
       func setHeight (object : AnyObject?){
       object.heightAnchor.constraint(equalToConstant : 75).isActive =      true
      }
    
      //Then do
         setHeight(object : label1)
    
     // you can expand the function for height and other things (: or change it to set all of them programmatically really quick