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
Just by telling [button invalidateIntrinsicContentSize];
, it should do what you are expecting it to do.
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 screenshot
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With