Autolayout - intrinsic size of UIButton does not include title insets

前端 未结 12 1113
不知归路
不知归路 2020-12-07 07:11

If I have a UIButton arranged using autolayout, its size adjusts nicely to fit its content.

If I set an image as button.image, the instrinsic size again

12条回答
  •  忘掉有多难
    2020-12-07 07:49

    I wanted to add a 5pt space between my UIButton icon and the label. This is how I achieved it:

    UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    // more button config etc
    infoButton.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 5);
    infoButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, -5);
    

    The way contentEdgeInsets, titleEdgeInsets and imageEdgeInsets relate to each other requires a little give and take from each inset. So if you add some insets to the title's left you have to add negative inset on the right and provide some more space (via a positive inset) on the content right.

    By adding a right content inset to match the shift of the title insets my text doesn't go outside the bounds of the button.

提交回复
热议问题