skip to Main Content

I have a Uitextfield, I want the leading and trailing to be 23 from the safe area or superview when the device width is less than 580 making it grow as wide as the device screen but 23 from both edges. But on devices with width greater than 580, I don’t want the uitextfield width to grow wider than 580. I want to have a max width of 580, and have it centered.

I tried setting the leading and trailing to be 23, and set the width <= 580, but it doesn’t work on iPads which have a device width greater than 580, instead, it grows very wide ignoring width<= 580 constraint. How can I achieve this in interface builder

2

Answers


  1. You need 4 horizontal constraints on the text field to meet your requirements:

    1. Set a constraint to center the text field in its parent view.
    2. Set the text field’s leading constraint to 23 but change the relation from = to >=.
    3. Set the text field’s trailing constraint to 23 but change the relation from = to >=.
    4. Set the text field’s width to 580 but lower the priority from 1000 to 750.

    On narrow screens the leading and trailing constraints take precedence over the width. This ensures the margins are 23 and the width fills in what’s left.

    On wider screens, the text field width gets no bigger than 580 and the >= setting of the margins allows the margins to be greater than 23. The center constraint ensures the text field stays centered.

    Login or Signup to reply.
  2. If you’re using the interface builder(Storyboard) use size class to achieve your need.

    Pin the textField (leading & trailing) to the edge if the device width is wC & hR and wC & hC, else set the width to 528 for wR and wR & hR.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search