Satish Mavani
Satish Mavani

Reputation: 5075

How to Increase/decrease UIButton width according to title lable text changes?

The Question I have asked is purely using auto-layout, I don't want to setup the frames manually according to text width.

I am aware of the changes Content hugging priority and I have used the same for one label and one button it works fine for the label but not for the button, can anyone help

Upvotes: 0

Views: 2901

Answers (3)

rob mayoff
rob mayoff

Reputation: 385610

The button already sets its “intrinsic content width” to fit its title.

If no other constraints override that intrinsic content width, the button will be that intrinsic width, which is what you want. Demo:

demo

Here's my storyboard outline:

storyboard outline

I set the Alignment of the horizontal stack view to “Left” (instead of “Fill”) so it wouldn't stretch the top row to fill the screen width.

If your button is not at its intrinsic width, you have higher-priority (probably priority 1000) constraints forcing it to some other width.

You can try to force it to always stay at its intrinsic content width by setting both its Content Hugging Priority and its Content Compression Resistance Priority to 1000.

If you set both priorities to 1000, and you have any other required constraints that prevent the button from being its intrinsic size, you will get error messages in the debug log at runtime telling you that you have conflicting (unsatisfiable) constraints. These messages will include the full set of constraints, so you can try to track down what constraints you have that you don't want.

Upvotes: 1

Nikhlesh Bagdiya
Nikhlesh Bagdiya

Reputation: 4466

Autolayout constraints

  • UILabel object's width constraint should be a Less Than or Equal relation
  • UIButton object's width constraint should be a Greater Than or Equal relation
  • UILabel object's horizontal Content Hugging Priority should be 249 (as per my constraint settings shown above)
  • And set UILabel width constant value as maximum possible value as your requirement.

And related code as:

[buttonObject setTitle:@"Button title is ..." forState:UIControlStateNormal];
[buttonObject sizeToFit];

Upvotes: 0

Sumeet Mourya
Sumeet Mourya

Reputation: 434

If you want to do this, you can create the custom View: Take - UIView and change it's class to UIButton and Add the UILabel and apply all required constraints. With this all setup you can achieve the desire UI. Please try this If you want to implement like this.

Upvotes: 0

Related Questions