Access NSLayoutConstraint size class value from IBOutlet

I have a Bottom Layout vertical space Constraint with size class variation for iPad and iPod. Please check the attached image

iPad = 62

iPod = 0.


Trying to access the Constraint value in the viewcontroller by IBOutlet reference.


Single constraint with different size class values for iPad and iPod as

Constant = 62

wC hR = 0.


I dont want to create two different constraints for iPad and iPod as I prefer single IBOutlet with different size class values.

But unable to read the size class values from NSLayoutConstraint, only getting constant value.




IBOutlet weak var stackViewBottomConstraint: NSLayoutConstraint!
 var bottomHeight = stackViewBottomConstraint.constant
 print("bottomHeight:\(bottomHeight)")

//bottomHeight: 62 - iPad
//bottomHeight: 62 - even for iPod


How to access the size class value of the constraint in the right way?


Replies

With help from

// https://stackoverflow.com/questions/29528661/ ios-detect-current-size-classes-on-viewdidload


I did the following:



enum DeviceTraitStatus {
    ///IPAD and others: Width: Regular, Height: Regular
    case wR
    case wC
    case hR
    case hC
    case wRhR
    ///Any IPHONE Portrait Width: Compact, Height: Regular
    case wChR
    ///IPHONE Plus/Max Landscape Width: Regular, Height: Compact
    case wRhC
    ///IPHONE landscape Width: Compact, Height: Compact
    case wChC

    static var current:DeviceTraitStatus {

        switch (UIScreen.main.traitCollection.horizontalSizeClass, UIScreen.main.traitCollection.verticalSizeClass){

        case (UIUserInterfaceSizeClass.regular, UIUserInterfaceSizeClass.unspecified):
            return .wR
        case (UIUserInterfaceSizeClass.compact, UIUserInterfaceSizeClass.unspecified):
            return .wC
        case (UIUserInterfaceSizeClass.unspecified, UIUserInterfaceSizeClass.regular):
            return .hR
        case (UIUserInterfaceSizeClass.unspecified, UIUserInterfaceSizeClass.compact):
            return .hC

        case (UIUserInterfaceSizeClass.regular, UIUserInterfaceSizeClass.regular):
            return .wRhR
        case (UIUserInterfaceSizeClass.compact, UIUserInterfaceSizeClass.regular):
            return .wChR
        case (UIUserInterfaceSizeClass.regular, UIUserInterfaceSizeClass.compact):
            return .wRhC
        case (UIUserInterfaceSizeClass.compact, UIUserInterfaceSizeClass.compact):
            return .wChC
        default:
            return .wChR
        }
    }
}

Then you can use as follows:

        let dts = DeviceTraitStatus.current
        if dts == .wChR  {     //
          stackViewBottomConstraint.constant = 0
        } else {
          stackViewBottomConstraint.constant = 62
       }