如何在Swift中更改按钮标题对齐方式?


76

我正在尝试将按钮的标题设置在左侧。但是我尝试的所有方法都无法正常工作。

带有:

UILabelButton.titleLabel.textAlignment = .Left

要么:

UILabelButton.contentVerticalAlignment = UIControlContentVerticalAlignment // There is no left

按钮标题仍居中。

还有其他财产吗?

Answers:


202

使用contentHorizontalAlignment。您必须使用UIControlContentHorizontalAlignment.Left。您需要使用horizontalnot vertical

btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left

斯威夫特3.x

btn.contentHorizontalAlignment = .left

2
如果将按钮的文本/内容换成两行,则@codester .center似乎不起作用。我们如何集中titleLabel包装的按钮的两行?
user2363025 '18

20

斯威夫特4

样例代码

对于我的要求,我想对准 顶部

btnAddress.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left
btnAddress.contentVerticalAlignment = UIControlContentVerticalAlignment.top

Swift 5更新:

btnAddress.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.left
btnAddress.contentVerticalAlignment = UIControl.ContentVerticalAlignment.top

1
    btnAddress.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.left
    btnAddress.contentVerticalAlignment = UIControl.ContentVerticalAlignment.top 

现在,如果您希望文本从左侧开始留一些空间,请添加此

btnAddress.titleEdgeInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.