Autolayout - intrinsic size of UIButton does not include title insets

前端 未结 12 1106
不知归路
不知归路 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:50

    This thread is a bit old, but I just ran into this myself and was able to solve it by using a negative inset. For example, substitute your desired padding values here:

    UIButton* myButton = [[UIButton alloc] init];
    // setup some autolayout constraints here
    myButton.titleEdgeInsets = UIEdgeInsetsMake(-desiredBottomPadding,
                                                -desiredRightPadding,
                                                -desiredTopPadding,
                                                -desiredLeftPadding);
    

    Combined with the right autolayout constraints, you end up with an auto-resizing button which contains an image and text! Seen below with desiredLeftPadding set to 10.

    Button with image and short text

    Button with image and long text

    You can see that the actual frame of the button doesn't encompass the label (since the label is shifted 10 points to the right, outside the bounds), but we've achieved 10 points of padding between the text and the picture.

提交回复
热议问题