Search code examples
iosswiftstoryboarduitextfielduipickerview

White Spaces using hidden for text field


I have a form with many Label and text Field, I want to show some Text Field only when a Picker View was selected, so I use hidden = true to hide my items, but there's a gap between two text fields because the middle the text field is hidden. How do I do it so I don't have a blank space ?

Screen:

picture 1

picture 2


Solution

  • You can accomplish what you want by using Auto Layout constraints with differing priorities.

    1. Add a vertical constraint from the top of label 3 to the bottom of field 2 and give that a constant of 8 and a priority of 998.
    2. Add a vertical constraint from the top of label 3 to the bottom of field 1 and give that a constant of 8 and a priority of 997.
    3. Add an @IBOutlet to the constraint in step 2 to your code. You can do this by finding the constraint in the Document Outline and control-dragging to your code. Call it something like field3Top.
    4. When it is time to hide field 2, set the hidden property for your text field 2 and label 2 to true and change the priority of fieldTop.priority to 999. This will cause this constraint to have priority over the other one and the gap will be closed.

      @IBOutlet weak var field3Top: NSLayoutConstraint!
      @IBOutlet weak var field2Label: UILabel!
      @IBOutlet weak var field2TextField: UITextField!
      
      field3Top.priority = 999
      field2Label.hidden = true
      field2TextField.hidden = true
      
      // for fun, you can animate the change with this code
      UIView.animateWithDuration(1.0) {
          self.view.layoutIfNeeded()
      }
      
    5. When it is time to show field 2 again, set field3Top.priority = 997 and set the hidden properties back to false.


    Here's a demo of the hiding in action:

    demo of hiding a field