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

查看:18
本文介绍了自动布局 - 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.

如何确保按钮的内在宽度占插图?

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天全站免登陆