在Swift中以编程方式更改UIButton的文本(填充)。

68

我仍在学习Swift, 不熟悉Objective-C。我看到想要通过编程改变按钮文本的方式需要使用titleEdgeInsets, 但是我不太确定如何使用它。

我想改变按钮文本(间距)的下方、左侧和右侧。

感谢任何回复和/或示例!

8个回答

174

仍适用于: iOS 12/Xcode 10/Swift 4.2/OSX 10.13.2


iOS 9.1/Xcode 7.1/Swift 2.1/OSX 10.10.5:

titleEdgeInsets 方法对我无效。我的按钮框紧贴着文本(我没有指定框架大小),框架有红色背景颜色。在执行以下操作后:

 myButton.titleEdgeInsets = UIEdgeInsetsMake(10,10,10,10)

红色背景向内收缩了每边10像素,这意味着现在一些文字已经超出了红色背景。使用负值对原框架大小没有影响。

我可以通过以下方式获得文本周围的填充,有效地使框架变大:

myButton.contentEdgeInsets = UIEdgeInsetsMake(5,5,5,5) 

1
@Nik Kov,谢谢。 - 7stud
2
新方法被称为:UIEdgeInsets.init(top: #, left:#, :bottom: #, right: #)。 - Andrey Solera
1
@Andrea,UIEdgeInsetsMake()仍然在文档中:https://developer.apple.com/documentation/uikit/1624475-uiedgeinsetsmake?language=occ - 7stud
2
@Andrea,如果您调用 UIEdgeInsetsMake(5,5,5,5),您会收到警告吗? - 7stud
4
titleEdgeInsets在iOS 15中已被弃用 :( - Raildex

64

iOS 10 和 Swift 3示例

在iOS 11和Swift 4上经过测试并正常工作。

refineButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 0, bottom: 0, right: 0)

5
如果文本被截断了,使用titleEdgeInsets时,请将其替换为contentEdgeInsets - Nike Kov
请注意,contentEdgeInsets在iOS 15中已被弃用。 - dwu39

32

您可以通过以下代码添加来自上方、左侧、右侧和底部的填充。

button.titleEdgeInsets.left = 10; // add left padding.
button.titleEdgeInsets.right = 10; // add right padding.
button.titleEdgeInsets.top = 10; // add top padding.
button.titleEdgeInsets.bottom = 10; // add bottom padding.

27
你也可以在Storyboard中这样做:
在这里输入图片描述


2
问题指定“以编程方式” - Ahmed Eid
7
我不会假装提供最佳答案,只是为了提供完整的信息。 - Nike Kov
6
有用,@aeid有时我搜索“programmatically”,因为在storyboard中找不到它。 - andrewtweber
我没有搜索编程或故事板,因为我无论如何都不在意。很高兴知道它在那里。 - froggomad

6

针对iOS 9.1/Xcode 7.1/Swift 2.1

@IBOutlet weak var ratingButton: UIButton!

override func viewDidLoad() {
    ratingButton.contentEdgeInsets = UIEdgeInsets(top:15,right:10,bottom:15,left:10)

    super.viewDidLoad()
}

0
在iOS 15中,contentEdgeInsets已被弃用,因此您需要使用以下方法...
var configuration = UIButton.Configuration.plain() // there are several options to choose from instead of .plain()
configuration.contentInsets = NSDirectionalEdgeInsets(top: 24, leading: 24, bottom: 24, trailing: 24)
button.configuration = configuration

-1

如果您不想每次创建按钮时都定义属性,可以使用自定义类;

class UIPaddedButton: UIButton {
  let padding = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)

  required init?(coder: NSCoder) {
    super.init(coder: coder)
  }

  override init(frame: CGRect) {
    super.init(frame: frame)
  }

  override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
    return contentRect.inset(by: padding)
  }
}

当进行初始化时;

let btn = UIPaddedButton()

1
这并不是完全正确的。调整titleRect相当困难。你必须遵循类似于这个过程:https://dev59.com/514c5IYBdhLWcg3w3dV_#58876988 - Fattie

-2

适用于 xcode 13.4 和 iOS 12 经过测试,可行 使按钮两侧留出空间

ButtonName.contentEdgeInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)

不幸的是,完全错误,已被弃用 :/ - Fattie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接