Search code examples
iosdynamicuibuttonsizetofit

Adjusting the width of a UIButton depending on its title


I have a lot of trouble solving this. I have the following situation. In my storyboard I have a table view and in the table view cell I have a UIButton and another UIButton next to it. The first button has text and the second button has a star image. I would like the following:

  1. I would like to have the first button to adjust its width depending on its text/title.

  2. I would like the second button's position to move along against the trailing space of the first button

I tried multiple suggestions with sizetofit(), but can't seem to get it right


Solution

  • Using Autolayout you don't have to worry about resizing the button yourself. Here's a quick layout to illustrate:

    Text and info button

    I've added a text button and a small round button simulating your star. In the interface builder in Xcode, I give the first button constraints for:

    • Fixed height
    • Fixed space to the left side of the view
    • Fixed space to the top side of the view

    enter image description here

    Then my second round button gets the following constraints:

    • Fixed width and height
    • Fixed horizontal space to the text button
    • Vertical alignment centered with the text button

    enter image description here

    Now when I set a long title for my button in code, you'll see that they follow each other in the way you describe:

    enter image description here