自动布局 - UIButton 的固有大小不包括标题插图 [英] Autolayout - intrinsic size of UIButton does not include title insets

查看:15
本文介绍了自动布局 - UIButton 的固有大小不包括标题插图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个使用自动布局排列的 UIButton,它的大小会很好地调整以适应它的内容.

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

如果我将图像设置为 button.image,则内部尺寸似乎再次说明了这一点.

If I set an image as button.image, the instrinsic size again seems to account for this.

但是,如果我调整按钮的 titleEdgeInsets,布局不会考虑到这一点,而是会截断按钮标题.

However, if I tweak the titleEdgeInsets of the button, the layout does not account for this and instead truncates the button title.

如何确保按钮的固有宽度占 inset 的比例?

How can I ensure that the intrinsic width of the button accounts for the inset?

我正在使用以下内容:

[self.backButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0)];

目标是在图像和文本之间添加一些分隔.

The goal is to add some separation between the image and the text.

推荐答案

您可以解决这个问题,而无需重写任何方法或设置任意宽度约束.您可以按如下方式在 Interface Builder 中完成所有操作.

You can solve this without having to override any methods or set an arbitrary width constraint. You can do it all in Interface Builder as follows.

  • 固有按钮宽度是由标题宽度加上图标宽度加上左右内容边缘插入得出的.

如果按钮同时包含图像和文本,则它们将作为一个组居中,中间没有填充.

If a button has both an image and text, they’re centered as a group, with no padding between.

如果您添加左侧内容插入,它是相对于文本计算的,而不是文本 + 图标.

If you add a left content inset, it’s calculated relative to the text, not the text + icon.

如果您设置负左图像插入,图像被拉到左侧,但整体按钮宽度不受影响.

If you set a negative left image inset, the image is pulled out to the left but the overall button width is unaffected.

如果您设置一个负的左侧图像插入,实际布局将使用该值的一半.因此,要获得 -20 点的左插图,您必须在 Interface Builder 中使用 -40 点的左插图值.

If you set a negative left image inset, the actual layout uses half that value. So to get a -20 point left inset, you must use a -40 point left inset value in Interface Builder.

所以你提供了一个足够大的左侧内容插图,以便为所需的左侧插图图标和文本之间的内部填充创建空间,然后将图标向左移动两倍的数量图标和文本之间的填充.结果是一个左右内容插入相等的按钮,以及一组居中的文本和图标对,它们之间具有特定的填充量.

So you provide a big enough left content inset to create space for both the desired left inset and the inner padding between the icon and the text, and then shift the icon left by doubling the amount of padding you want between the icon and the text. The result is a button with equal left and right content insets, and a text and icon pair that are centered as a group, with a specific amount of padding between them.

一些示例值:

// Produces a button with the layout:
// |-20-icon-10-text-20-|
// AutoLayout intrinsic width works as you'd desire.
button.contentEdgeInsets = UIEdgeInsetsMake(10, 30, 10, 20)
button.imageEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0)

这篇关于自动布局 - UIButton 的固有大小不包括标题插图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆