Trouble left-aligning UIButton title (iOS/Swift)

stumped picture stumped · Apr 7, 2016 · Viewed 23.3k times · Source

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)

enter image description here

Answer

OhNo picture OhNo · Apr 7, 2016

Try this:

button.contentHorizontalAlignment = .left