Search code examples
swiftiphoneif-statementipadconstraints

changing constraints of object based on ipad or iphone


In my code to reach the desired effect i can only do it if I change the constraints based on whether the using a iphone or ipad. So i need to create something like if iphone constraints = and then if ipad constraints. I wrote a example of what I needed to do. I just need to change the the last line of the 4 statments controlling the bottom ancor.

     //ipad
     NSLayoutConstraint.activate([
        
        box.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.25),
        box.widthAnchor.constraint(equalTo: view.widthAnchor,multiplier: 0.10),
        box.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        box.centerYAnchor.constraint(equalTo: view.centerYAnchor),

      ])

 //iphone
     NSLayoutConstraint.activate([
        
        box.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.25),
        box.widthAnchor.constraint(equalTo: view.widthAnchor,multiplier: 0.10),
        box.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        box.bottomAnchor.constraint(equalTo: view.centerYAnchor),

      ])

Solution

  • Check the size class. For ipads, the horizontal and vertical classes should both be regular. You could do something like the following:

        let horizontalSizeClass = view.traitCollection.horizontalSizeClass
        let verticalSizeClass = view.traitCollection.verticalSizeClass
    
        switch horizantalSizeClass {
        case .regular:
            // Do some layout.
        case .compact:
            // Make compact constraints...
        default:
            // Unspecified. Do something else.
        }
        
        // rest of setup
    

    Also, the reason you couldn't make any constraints for was because you typed in break which ends the switch statement. The other answer might work.