UIButton标题左对齐出现问题(iOS/Swift)

45

我有一个问题,就是左对齐UIButton的文本。我也尝试将其更改为.Right,但它仍然保持居中。我还尝试了aButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0)而不是aButton.titleLabel?.textAlignment = .Left,但这也没有改变任何东西。是否有其他方法以编程方式更改UIButton标题的对齐方式?

        allButtonViews = UIView(frame: CGRectMake(0, 44, 100, 100))
        allButtonViews.backgroundColor = .redColor()

        let campusButton = UIButton(type: UIButtonType.System) as UIButton
        aButton.frame = CGRectMake(0, 0, 300, 70)
        aButton.setTitle("A", forState: .Normal)
        aButton.titleLabel?.textColor = .blueColor()
        aButton.titleLabel?.textAlignment = .Left
        aButton.backgroundColor = .whiteColor()

        sortView.addSubview(aButton)
        view.addSubview(allButtonViews)

输入图像描述

2个回答

160

试一试:

button.contentHorizontalAlignment = .left

在Xcode中是否有任何设置可以启用相同的功能? - bibscy
添加一个用户定义的运行时属性,其中contentHorizontalAlignment是一个NSNumber,其值为0-3,分别表示居中、左对齐、右对齐和填充。 - GonzoCoder
6
已将 "Left" 重命名为 ".left"。 - Ian Bradbury

21

已更新至 Swift 3 或 Swift 4

yourButton.contentHorizontalAlignment = .left

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