如果给出插图,UIButton 宽度不会根据文本增加

UIButton width doesn't increase based on text if insets are given

我已经为按钮设置了 trailingtopheight 约束。 正如您在附带的屏幕截图中看到的那样,如果我删除所有给定的插图,那么按钮看起来很完美并且按钮适合基于文本长度。

但我想给 right-left 标题插图和左图插图。

然后按钮无法正确显示文本,如所附屏幕截图所示。

Auto-layout 在调整 UIButton.

的标题标签时可能有点棘手

来自 Apple 的 titleEdgeInsets 文档:

This property is used only for positioning the title during layout. The button does not use this property to determine intrinsicContentSize and sizeThatFits(_:).

你有几个选择...

一个是继承 UIButton 并覆盖 .intrinsicContentSize.

另一种可能更适合您情况的选项是调整 Content Insets 而不是 Title Insets

如您所述,此按钮具有顶部/尾部/高度限制:

请注意,图像插图的左值是 负值 值。您可能/可能会想要调整我使用的值。