我仍在学习Swift, 不熟悉Objective-C。我看到想要通过编程改变按钮文本的方式需要使用titleEdgeInsets
, 但是我不太确定如何使用它。
我想改变按钮文本(间距)的下方、左侧和右侧。
感谢任何回复和/或示例!
仍适用于:
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)
iOS 10 和 Swift 3示例
在iOS 11和Swift 4上经过测试并正常工作。
refineButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 0, bottom: 0, right: 0)
titleEdgeInsets
时,请将其替换为contentEdgeInsets
。 - Nike KovcontentEdgeInsets
在iOS 15中已被弃用。 - dwu39您可以通过以下代码添加来自上方、左侧、右侧和底部的填充。
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.
针对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()
}
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
如果您不想每次创建按钮时都定义属性,可以使用自定义类;
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()
适用于 xcode 13.4 和 iOS 12 经过测试,可行 使按钮两侧留出空间
ButtonName.contentEdgeInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
UIEdgeInsetsMake(5,5,5,5)
,您会收到警告吗? - 7studtitleEdgeInsets
在iOS 15中已被弃用 :( - Raildex