Weakman10122
Weakman10122

Reputation: 391

iOS layout: How to keep a button in the middle an image?

I have an image that needs a UITextField in the middle of it at all times. However, I can't get it do what I want.

I pinned the image with top, left and right constraint and gave it a height constraint. I put the UITextField in the middle of the image and tried various methods to keep it in the middle, but they all keep failing. Any tips are appreciated. Here is what the image currently looks like. First one iPhone 4 and second one is iPhone 6

enter image description here

enter image description here

Upvotes: 0

Views: 171

Answers (2)

rob mayoff
rob mayoff

Reputation: 385860

You can just select the image view and the button and create two constraints: a “Horizontal Centers” constraint and a “Vertical Centers” constraint. Neither view has to be a subview of the other, and they don't have to be in the same superview either.

Here's a demo. I've already constrained the image view to fill the top left quadrant of the root view, and I've dragged in a button. In the demo I'll select the image view and the button (hold shift to select multiple views) and create the two centering constraints. Then I'll use the Preview assistant to show that the button stays centered when the image view's frame changes.

demo of centering constraints

Upvotes: 1

JLT
JLT

Reputation: 3172

What you need to do:

  • Embed the UIImageView and UITextField inside a UIView.
  • Set constraints of UIImageView leading, trailing, top, and bottom to UIView with constant of 0.
  • Set constraints of UITextField center horizontally with container view, and center vertically with container view.

Then it's up to you on where you want to position that UIView. This will definitely always position the UITextField to the center of UIImageView.

Upvotes: 0

Related Questions