Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intrinsic size not updating when changing UIButton state

I have a UIView that contains a UIButton. The UIButton has 2 titles set for the UIControlStateNormal ("Follow") and UIControlStateSelected ("Following") states. I am using auto layout on the UIButton and it has a constraint to be a certain distance from the top of the superview and another to be a certain distance from the left side of the superview. I've also used "Size to fit Content" on it.

When I set the button to be in the selected state from code, the title changes correctly but the intrinsic width of the UIButton doesn't change so that when changing from "Follow" to "Following" the text gets ellipsized.

self.selected = self.following;

enter image description hereenter image description here

When I approach the problem differently and simply change the text for UIControlStateNormal when someone hits the button, the button changes size correctly.

NSString *title = (self.following) ? @"Following" : @"Follow"
[self setTitle:title forState:UIControlStateNormal];

enter image description hereenter image description here

Is this a bug in UIKit? I would expect the button to change its intrinsic size to correctly reflect the new size of the text when its state changes especially because there are other things I would like to change besides just the text for the 2 button states.

like image 243
jvergeldedios Avatar asked Jul 31 '13 22:07

jvergeldedios


People also ask

How does a view's intrinsic content size aid in auto layout?

In general, the intrinsic content size simplifies the layout, reducing the number of constraints you need. However, using the intrinsic content size often requires setting the view's content-hugging and compression-resistance (CHCR) priorities, which can add additional complications.

What is intrinsic content size?

Intrinsic content size is information that a view has about how big it should be based on what it displays. For example, a label's intrinsic content size is based on how much text it is displaying. In your case, the image view's intrinsic content size is the size of the image that you selected.


2 Answers

Like David Caunt pointed out in a comment, calling invalidateIntrinsicContentSize will cause autolayout to resize the button to fit it's new content.

self.selected = self.following;
[self invalidateIntrinsicContentSize];

PS. David, if you want to post your commant as an answer I will remove mine.

like image 71
akelagercrantz Avatar answered Sep 20 '22 11:09

akelagercrantz


In your storyboard select your UIButton and on top select editor->size to fit content size.

EDIT: Try this:

[self.myButton setTitle:@"Following" forState:UIControlStateSelected];
[self.myButton sizeToFit];
like image 34
Abdullah Shafique Avatar answered Sep 18 '22 11:09

Abdullah Shafique