我在给UIButton
添加左内边距方面遇到了麻烦。我有一个UIControlContentHorizontalAlignmentLeft
的UIButton
,我希望文本显示在左侧,但是它太靠左了。当我设置边框时,效果不好。我想给文本大约5像素的内边距,就像在CSS中一样。我在谷歌上搜索解决方案,但没有找到特别针对UIButton
的解决方案。
我在给UIButton
添加左内边距方面遇到了麻烦。我有一个UIControlContentHorizontalAlignmentLeft
的UIButton
,我希望文本显示在左侧,但是它太靠左了。当我设置边框时,效果不好。我想给文本大约5像素的内边距,就像在CSS中一样。我在谷歌上搜索解决方案,但没有找到特别针对UIButton
的解决方案。
titleEdgeInsets:按钮标题绘制矩形的内边距或外边距。
@property(nonatomic) UIEdgeInsets titleEdgeInsets
Discussion:使用此属性来调整并重新定位按钮标题的有效绘制矩形。您可以为每个边缘(上、左、下、右)指定不同的值。正值会缩小该边缘,即将其插入到按钮中心更近的位置。负值会扩展该边缘。使用UIEdgeInsetsMake函数构造此属性的值。默认值为UIEdgeInsetsZero。
Availability:在iOS 2.0及更高版本中可用。
声明于UIButton.h
试一下吧 :)
[myButton setTitleEdgeInsets:UIEdgeInsetsMake(0.0, 5.0, 0.0, 0.0)];
如果你正在使用自定义按钮,那么可能会涉及到内容插图和图像插图。
如果你是在寻找Swift方面的帮助,那么这段代码适用于Swift 3.0版本。
myButton.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: 5.0, bottom: 0.0, right: 0.0)
你也可以直接设置它。这对于想要使用一两个属性很有帮助。
myButton.titleEdgeInsets.top = 0
myButton.titleEdgeInsets.left = 5
myButton.titleEdgeInsets.bottom = 0
myButton.titleEdgeInsets.right = 0
myButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 5.0, bottom: 0, right: 0)
- Nathaniel以下是更好的答案,用于:
代码:
extension UIButton {
func addLeftPadding(_ padding: CGFloat) {
titleEdgeInsets = UIEdgeInsets(top: 0.0, left: padding, bottom: 0.0, right: -padding)
contentEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: padding)
}
}
用法:
myButton.addLeftPadding(10)
let sidePadding: CGFloat = 20.0 titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -sidePadding, bottom: 0.0, right: -sidePadding) contentEdgeInsets = UIEdgeInsets(top: 0.0, left: sidePadding, bottom: 0.0, right: sidePadding)
。 - Arthur ClemenscontentEdgeInsets = UIEdgeInsets(top: 0.0, left: padding, bottom: 0.0, right: padding)
就可以解决这个问题。 - Nike Kov在 Xcode 6 中,你可以在 IB 中指定标题插入:
[self.myButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
float padding_button = 6.0f;
UIEdgeInsets titleInsets = UIEdgeInsetsMake(0.0f, padding_button, 0.0f, -padding_button);
UIEdgeInsets contentInsets = UIEdgeInsetsMake(padding_button, 0.0f, padding_button, 0.0f);
CGFloat extraWidthRequiredForTitle = titleInsets.left - titleInsets.right;
contentInsets.right += extraWidthRequiredForTitle;
[self.myButton setTitleEdgeInsets:titleInsets];
[self.myButton setContentEdgeInsets:contentInsets];
[self.myButton sizeToFit];
[self.myButton setImage:[UIImage imageNamed:@"YourImage.png"] forState:UIControlStateNormal];
Good luck!
_myButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
_myButton.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
titleEdgeInsets 现已弃用
所以您可以使用 UIButton.Configuration https://developer.apple.com/documentation/uikit/uibutton/configuration/
var configuration = UIButton.Configuration.plain()
configuration.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 0)
myButton.configuration = configuration