Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton dynamic width using autolayout

I am having a button which has two different text in selected state and normal state, When I change state of button programatically button is not getting resized so text is not appearing properly, which is the best way to do this with autolayout?

I know one way setting outlet to UIButton's width constraint and change it manually but I am looking for better way

like image 760
Abhishek Avatar asked Oct 30 '14 11:10

Abhishek


2 Answers

Just by telling [button invalidateIntrinsicContentSize];, it should do what you are expecting it to do.

like image 115
Srikanth Avatar answered Oct 28 '22 13:10

Srikanth


An alternate way for shrinking/expanding width of UIButton using autolayout is to add a width constraint and then change the priority of width constraint to less than Content Hugging Priority and Content Compression Resistance Priority.

In case we only want to expand the button based on their title, we can set the width constraint to the minimum value and the priority of width constraint to less than Content Compression Resistance Priority but more than Content Hugging Priority.

In the above cases we only need to

btn.setTitle("SomeTitle", for: .normal)

in the code and auto layout will take care of the rest.

Attached is a screenshotenter image description here

like image 22
Hassaan Fayyaz Avatar answered Oct 28 '22 12:10

Hassaan Fayyaz