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;
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];
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.
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.
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.
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.
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];
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