Ben_hawk
Ben_hawk

Reputation: 2486

Xcode 6 auto layout flexible width

I have a UITextField which using Xcode 6s auto layout interface I have set to have a width of 400 points. This looks fine on larger screen devices but on the iPhone 5s these boxes disappear out of the containing view. What is the correct way to approach this?

Is there a way to set a constraint that will make the UITextFields width 400 points if the screen is large than this or just fill the container view if not, instead of overflowing outside of the view or should I be using the size classes to set the UITextField to have equal widths to its parent view on compact views.

Upvotes: 2

Views: 3958

Answers (2)

mbm29414
mbm29414

Reputation: 11598

Like what Kris said, setting up Horizontal Space constraints is a great way to get started on this issue.

In response to your comment about not wanting constant "margins", you can do the following:

  1. Set up Horizontal Space constraints in Interface Builder.
  2. Create IBOutlets of type NSLayoutConstraint in your class (either .h or .m; it doesn't matter).
  3. Connect the IBOutlets to the respective NSLayoutConstraints.
  4. In one of your view lifecycle methods (viewDidLoad/viewWillAppear:), set up the constraints to your desired values.

It sounds like you mainly want to prevent the field from spanning the full screen on an iPad, so you could do something like this (assume NSLayoutConstraints are named "textFieldLeft" and "textFieldRight" for a UITextField named "textField"):

- (void)viewDidLoad {
    if (UI_USER_INTERFACE_IDIOM == UIUserInterfaceIdiomPad) {
        self.textFieldLeft.constant = 50.0f;
        self.textFieldRight.constant = 50.0f;
        [self.textField layoutIfNeeded];
    }
}

Upvotes: 0

Krys Jurgowski
Krys Jurgowski

Reputation: 2911

Instead of setting the width constraint on the UITextField, add Horizontal Space constraints to the left and right of it. That way the UITextField will size automatically with the screen.

Upvotes: 2

Related Questions