-->

Trouble left-aligning UIButton title (iOS/Swift)

2019-03-22 15:56发布

问题:

I'm having a problem left-aligning a UIButton's text. I also tried changing it to .Right but it still stays centered. I also tried aButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0) instead of aButton.titleLabel?.textAlignment = .Left but that doesn't change anything either. Is there an alternative way to programmatically change the alignment of a UIButton title's?

        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)

回答1:

Try this:

        button.contentHorizontalAlignment = .Left


回答2:

Updated for Swift 3 or Swift 4

yourButton.contentHorizontalAlignment = .left


回答3:

For Swift 4;

    locationButton.contentHorizontalAlignment = .left