0

I actually updated the extension below (found here: Size class specifically for portrait 3.5 inch (iPhone 4S) XCode 6? ) for Swift 5.0, and it works except when the constraint being modified has a "vary for traits" property and I cannot figure out why?

extension NSLayoutConstraint
{
    //We use a simple inspectable to allow us to set a value for iphoneSE / 5s.
    @IBInspectable var iPhoneSE_PortraitConstant: CGFloat
        {
        set{
            //Only apply value to iphone SE and 5s devices.
             if (UIScreen.main.bounds.size.height < 660 && UIScreen.main.bounds.size.width < 330)
            {
                self.constant = newValue;
            }
        }
        get
        {
            return self.constant;
        }
    }
}

I'm guessing that Xcode is first finding the constraint and them seeing if it has a Vary for Traits addition and for this reason ignores the extension? How can I get past this?

Rillieux
  • 587
  • 9
  • 23

1 Answers1

0

Based on quick testing, it appears the order goes like this:

  • XIB gets loaded (Storyboard is effectively a big XIB)
  • User Defined Run Time Attributes are applied (this would be your iPhoneSE_PortraitConstant) which sets the .constant of the constraint
  • Auto-layout does its thing
  • Auto-layout sets the .constant of the constraint, based on Traits, if they exist (it does not set the iPhoneSE_PortraitConstant property)

So, that extension won't work if the constraint itself has trait variations.

The key, there, is the constraint itself.

To get this approach to work, instead of setting trait variations on the constraint, set trait variations on the view and have two (or more) separate constraints. Then set the iPhoneSE_PortraitConstant on the constraint(s) as needed.

DonMag
  • 69,424
  • 5
  • 50
  • 86