Eduard
Eduard

Reputation: 3576

How to make a full-width UITextField in Swift

I'm very new to Swift, like one week new and I'd like to come up with a 100% width UITextField. The expected result is that the text field should be 100% of the screen's width.

This is what I've done for iPhone 5 displays having a 320px vertically centered TextField.

enter image description here

That looks as expected, but when I'm going on iPhone 6, this happens: enter image description here

How is it possible to make this 100% of the screen's width? As I can only see fixed width inputs in size inspector.

Upvotes: 5

Views: 12031

Answers (2)

luk2302
luk2302

Reputation: 57114

You should not specify the width but the leading and trailing space of the textfield to its superview:

  • select the UITextField you want to align
  • click on the Pin icon
  • uncheck the "Constrain to margins"
  • set the leading to 0
  • set the trailing to 0

enter image description here

which will result in the TextField to span the entire width on every screen:

enter image description here

Note that you sometimes have to specify the view you want to set the space relative to:

enter image description here

Upvotes: 14

Daniel Krom
Daniel Krom

Reputation: 10058

You can use auto layout and constraints,

if you wish, you can do it manually using code:

//full screen size
let screenWidth = UIScreen.mainScreen().bounds.width
textInput.frame.size.width = screenWidth

Upvotes: 2

Related Questions