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

查看:420
本文介绍了自动布局 - 的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天全站免登陆