麻烦左对齐UIButton标题(iOS / Swift)

时间:2016-04-07 00:36:33

标签: swift uibutton title text-alignment leftalign

我遇到问题左对齐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)

enter image description here

3 个答案:

答案 0 :(得分:93)

试试这个:

        button.contentHorizontalAlignment = .Left

答案 1 :(得分:12)

针对Swift 3或Swift 4进行了更新

yourButton.contentHorizontalAlignment = .left

答案 2 :(得分:4)

Swift 4 ;

    locationButton.contentHorizontalAlignment = .left