Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton takes up its own size Autolayout

What I tried was this :-

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[self.view addSubview:btn];
btn.translatesAutoresizingMaskIntoConstraints = NO;
[btn addTarget:self action:@selector(bringUpNextViewController:) 
                    forControlEvents:UIControlEventTouchUpInside];
btn.titleLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:14];
[btn setTitle:@"8" forState:UIControlStateNormal];
[self.view layoutIfNeeded];

NSLog(@"button size : %@", NSStringFromCGSize(btn.frame.size));

As output, I get this :

button size : {30, 29}

Then I gave setTitle string as nothing. The button width was still 30.

So why is this the case always?

I also tried giving a high compression resistance priority and high content hugging priority. Doesn't shrink to nothing.

The problem is also the fact that I want to reduce the width of the button simply based on its content, without giving any fixed width.

I could take the width of text and give the button the width, but I shouldn't be needing to do that either if the button was taking up the content width.

EDIT:

Its not the insets either which is causing the width to be 30. Ghost value.

like image 216
esh Avatar asked Apr 25 '14 06:04

esh


1 Answers

A button is made of several subviews. It's very likely that the internal layout of a button has some default padding between the label and the button view itself.

Making a button like yours and examining the constraints shows the following:

button constraints (
"<NSContentSizeLayoutConstraint:0x8c40a60 H:[UIButton:0x8f29840(30)] Hug:250 CompressionResistance:750>",
"<NSContentSizeLayoutConstraint:0x8c55280 V:[UIButton:0x8f29840(29)] Hug:250 CompressionResistance:750>"
)

The 30 and 29 tie up with the size values you are seeing. The intrinsic content size property of the button also returns 30,29. Basically this is the minimum size for a button, in the absence of anything else.

It's not quite clear what you want or why you are bothered by this. Anything smaller will be a poor touch target, and a button with no label or image will be invisible anyway. If you add a longer title, the button will get bigger. If you add other constraints to force particular sizes, then these will override the intrinsic content size.

If you want the button to become invisible when it has no title, then you should explicitly hide it. This makes your intentions in the code much clearer and will prevent the user from accidentally hitting a button they can't really see.

like image 133
jrturton Avatar answered Oct 06 '22 12:10

jrturton