Stephan
Stephan

Reputation: 2039

How to make a UITextView fill up the remaining space

I have a UIButton and UITextField side by side as follows.

enter image description here

I want the Add button to only have a width based on the content. And the text view shall take up the rest of the space. I have the following auto layout constraints.

private func setupLayout() {
    newDeviceIdTextField.topAnchor.constraint(equalTo: deviceIdLabel.bottomAnchor, constant: 12).isActive = true
    newDeviceIdTextField.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 12).isActive = true

    newDeviceIdButton.topAnchor.constraint(equalTo: deviceIdLabel.bottomAnchor, constant: 12).isActive = true
    newDeviceIdButton.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -12).isActive = true
    newDeviceIdButton.leadingAnchor.constraint(equalTo: newDeviceIdTextField.trailingAnchor, constant: 0).isActive = true
}

In this article there is a section which I believe exactly solves my problem. But I just don't understand how.

What am I missing here?

Upvotes: 0

Views: 1156

Answers (2)

Pratik Prajapati
Pratik Prajapati

Reputation: 1103

You can do this without writing code, from storyboard. What i do for this kind of UI is,

  1. Pin the left of the text field where you want it.

  2. Pin the right of the button where you want it.

  3. Pin the tops of both where you want them.

  4. Pin the right of the text field to the left of the button

It's look like in image below

enter image description here

Now Select button > Size Inspector > In Content hugging Priority

Change Horizontal to 750(high) and you done :)

enter image description here

Result look like in image below

enter image description here

Upvotes: 0

matt
matt

Reputation: 536027

A button automatically sizes its width to fit its content, and both a text field and a button have an automatic height. So what you want to do is trivial:

Pin the left of the text field where you want it.

Pin the right of the button where you want it.

Pin the tops of both where you want them.

Pin the right of the text field to the left of the button and set that constant to a small number such as 8.

Upvotes: 3

Related Questions