Nrc
Nrc

Reputation: 9787

Auto Layout TextField. Center, top

I try to understand auto layout. I have a Text field with 3 constraints: - Align Center X to: Superview - Top Space to: Superview 50 - Width Equals: 150 I have a warning: Equal constraints may cause clipping

If I change to - Width Greater Than or Equal 150 I have the warning: Width and horizontal position are ambiguous.

I am confused. In fact, those Constraints work well for a button or a label. - Why is it different for a TextField?
- How to position a TextField horizontal center, top 50, and width 150?

(It seems that I have to add a leading and trailing Greater Than or Equal. That seems redundant to the Width Greater Than or Equal 150. That works to silence the warning but that seems a solution too complicated and redundant. is that right?)

enter image description here

Upvotes: 0

Views: 363

Answers (2)

DonMag
DonMag

Reputation: 77423

I just checked this on:

  • Xcode 11.2.1
  • Xcode 11.4.1

The warning shows on 11.2.1 but does not show on 11.4.1

In my view, even though it is a valid warning, it was a silly one and appears to have been removed in the version update.

If you want a label to have a width of 150, of course you know the text will be clipped if it is too long. There is no way around that for a single-line label, unless you allow it to expand outside the bound of the window.

Again, that's a valid warning, but that may be exactly what you want.

If you want a text input field to have a width of 150, the text will scroll when you input too much to fit.

So, why the warning on a text field? No idea. That probably could be considered a bug.

You can get rid of that warning by giving your Width: 150 constraint a Priority: 250. Just single, quick test shows that the field width will remain at 150 even when typing too much text. But... I'd hate to rely on that assumption, and if the field width / leading / trailing etc is related to any other UI elements, I wouldn't count on it not causing other layout issues.

I would say (my opinion only) this is an IB warning that is safe to ignore.

Upvotes: 0

Frankenstein
Frankenstein

Reputation: 16341

It's because UILabel and UIButton adjusts its size according to its content. In this case, you need to specify a proper width or you can give a leading and trailing anchor with the desired padding.

Here's is how you can resolve your constraint issue in this particular case. Give the text field the following constraints:

  1. 50 points from the top.
  2. Leading from the super view with padding.
  3. Trailing anchor from the super view with padding.

The last two anchors can be replaced with these two constraints:

  1. Width constraint for the text field.
  2. Centre horizontally to the super view.

Here's how you achieve this on a story-board:

Constraint

Upvotes: 1

Related Questions