0

A common use case that can occur is needing to add a view for a specific size class. For example, wRegular.

We might want to add an extra label to take advantage of the extra space.

My question is where should I add this label, more specifically should we add this label to our view in the method below ?

traitCollectionDidChange


I was thinking of doing something like so

// sudo code
traitCollectionDidChange{

    if (wR){
        create special view if special view is nil 
        self.view.addChildView(special View) 
        set constraints for wRegular size class

     } else{
        self.view.removeChildView(special View) 
        deactivate special view constraints (if not nil)
        set constraints for ... size class 

     }
}

There seems to be tons of examples on how to do this in interface builder but I wasn't sure where we would actually initialize the extra view.

I initialized the special view in traitCollectionDidChange because we might have a device that will never need the special view.

3366784
  • 2,423
  • 1
  • 14
  • 27

1 Answers1

0

Don't add and remove view every time. Add it only once. Just activate and deactivate constraints based on trait inside traitCollectionDidChange like following code.

   if self.traitCollection.horizontalSizeClass == .compact {
     NSLayoutConstraint.activate(horConstraintsArray)
     NSLayoutConstraint.deactivate(vertConstraintsArray)
   } else {
     NSLayoutConstraint.activate(vertConstraintsArray)
     NSLayoutConstraint.deactivate(horConstraintsArray)
   }

Also, as per the code you wrote in else part, if view is removed, the constraints are automatically removed. As you rotate the device, creating and adding the view, adding constraints everytime is a costly task performance wise.

Bhagyesh
  • 144
  • 1
  • 8
  • What if we move from Regular width to Compact. In this case the view that we add is not needed. Shouldn't we need to remove it in that case ? Note: I'm not creating the view every-time, simply removing it from the main view. – 3366784 Dec 02 '17 at 09:46
  • A simple example is Apples calculator app. Rotate the view and you will see how they add new buttons. – 3366784 Dec 20 '17 at 08:10