如果我有一个UIButton安排使用自动布局,它的大小调整很好地适合它的内容。

如果我设置一个图像为按钮。图像,内在的大小似乎也解释了这一点。

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

我如何确保按钮的内在宽度占了嵌入?

编辑:

我正在使用以下:

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

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


当前回答

以上所有都无法在iOS 9+上运行,我所做的是:

添加宽度限制(当按钮没有任何文本时为最小宽度)。如果提供了文本,按钮将自动缩放) 将关系设置为大于或等于

现在要在按钮周围添加边框,只需使用下面的方法:

button.contentEdgeInsets = UIEdgeInsetsMake(0,20,0,20);

其他回答

我使用的解决方案是在按钮上添加宽度限制。然后在初始化的某个地方,在你的文本设置好之后,像这样更新宽度约束:

self.buttonWidthConstraint.constant = self.shareButton.intrinsicContentSize.width + 8;

8是你的插入数。

你没有指定如何设置insets,所以我猜你在使用titleEdgeInsets,因为我看到你得到了相同的效果。如果我使用contenttedgeinsets代替它正常工作。

- (IBAction)ChangeTitle:(UIButton *)sender {
    self.button.contentEdgeInsets = UIEdgeInsetsMake(0,20,0,20);
    [self.button setTitle:@"Long Long Title" forState:UIControlStateNormal];
}

你可以在Interface Builder中(不需要编写任何代码),通过使用消极和积极的标题和内容插入的组合来让它工作。

更新:Xcode 7有一个错误,你不能在右插入字段中输入负值,但你可以使用它旁边的步进控件来减小值。(感谢Stuart)

这样做将在图像和标题之间增加8pt的间距,并将增加相同数量的按钮的固有宽度。是这样的:

斯威夫特是这样做的:

extension UIButton {
    override open var intrinsicContentSize: CGSize {
        let intrinsicContentSize = super.intrinsicContentSize

        let adjustedWidth = intrinsicContentSize.width + titleEdgeInsets.left + titleEdgeInsets.right
        let adjustedHeight = intrinsicContentSize.height + titleEdgeInsets.top + titleEdgeInsets.bottom

        return CGSize(width: adjustedWidth, height: adjustedHeight)
    }
}

爱你斯威夫特

您可以解决这个问题,而不必重写任何方法或设置任意宽度约束。你可以在Interface Builder中完成这一切。

Intrinsic button width is derived from the title width plus the icon width plus the left and right content edge insets. 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. 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.

因此,您需要提供足够大的左侧内容插入,为所需的左侧插入和图标和文本之间的内部填充创造空间,然后通过将图标和文本之间的填充量增加一倍来将图标向左移动。结果是一个左右内容相同的按钮,文本和图标对作为一个组居中,它们之间有特定数量的填充。

一些示例值:

// 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)